typescript - use map

  • Commit 
https://github.com/shooeugenesea/study-js/commit/2d22117a7b36ea1225b960892995e409bbc5e64f
    https://github.com/shooeugenesea/study-js/commit/30cb24cd3a5dc57dde750fa6e90a04b88dba8084
    • Declare class with map
    • export class TestMap {
          private map: Map<string, string> = new Map();

          put(key:string, val:string): void {
              if (key) {
                  this.map.set(key, val);
              }
          }

          get(key:string): string | undefined {
              if (key) {
                  return this.map.get(key)
              }
          }

          count(): number {
              return this.map.size;
          }

          clearByKeyPrefix(prefix: string) {
              this.map.forEach((v: string, k:string, m:Map<string,string>) => {
                  if (k.startsWith(prefix)) {
                      m.delete(k);
                  }
              })
          }
      }
    • Put and get then print
    • const testMap = new TestMap();
      testMap.put("ka", "vka");
      testMap.put("kb", "vka");
      testMap.put("kc", "vka");
      testMap.put("kd", "vka");
      testMap.put("ke", "vka");
      testMap.put("aa", "vaa");
      console.log(testMap);
      console.log(testMap.count()); // 6
      testMap.clearByKeyPrefix("k"); // print 6 entries
      console.log(testMap.get("aa")); // print vaa


    沒有留言:

    張貼留言

    別名演算法 Alias Method

     題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...