TypeScript-实现一个字典

120 阅读1分钟

实现一个字典

目录结构

... /src 
......./index.ts 
......./dictionary.ts

dictionary.ts

export type Callback<K, V> = (key: K, val: V, index: number) => void;

export class Dictionary<K, V> {
  private keys: K[] = [];
  private vals: V[] = [];

  get size() {
    return this.keys.length;
  }

  set(key: K, val: V) {
    if (this.has(key)) {
      const inx = this.keys.indexOf(key);
      this.vals[inx] = val;
    } else {
      this.keys.push(key);
      this.vals.push(val);
    }
  }

  forEach(callback: Callback<K, V>) {
    this.keys.forEach((key, index) => {
      const v = this.vals[index];
      callback(key, v, index);
    });
  }

  has(key: K) {
    return this.keys.includes(key);
  }

  delete(key: K) {
    if (this.has(key)) {
      const inx = this.keys.indexOf(key);
      this.keys.splice(inx, 1);
      this.vals.splice(inx, 1);
    }
  }
}

index.ts

import { Dictionary } from "./dictionary";

const dic = new Dictionary<string, number>();

dic.set("a", 1);
dic.set("b", 2);
dic.set("a", 11);
dic.set("c", 33);

dic.forEach((k, v, index) => {
  console.log(`${k}:${v}  ${index}`);
});
console.log("当前键值对数量:" + dic.size);
console.log("删除键b");

dic.delete("b");

dic.forEach((k, v) => {
  console.log(`${k}:${v}`);
});
console.log("当前键值对数量:" + dic.size);

package.json

{
  "name": "demo001",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "@types/node": "^20.5.9"
  },
  "scripts": {
    "dev": "nodemon --watch src -e ts --exec ts-node src/index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

tsconfig.json

{
  /* 编译选项 */
  "compilerOptions": {
    "target": "ES2016" /* 配置编译目标代码的版本标准 */,
    "module": "commonjs" /* 配置编译目标使用的模块化标准 */,
    "lib": ["ES2016"] /* 编译的环境,不会有dom相关的API了 */,
    "outDir": "./dist" /* 编译的产物存放的位置 */,
    "strictNullChecks": true,
    "removeComments": true,
    "esModuleInterop": true,
    "noEmitOnError": true,
    "moduleResolution": "node",
    "strictPropertyInitialization": true
  },
  "include": ["./src"] /* 指定编译src下的所有ts文件 */
}