实现一个字典
目录结构
... /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"] ,
"outDir": "./dist" ,
"strictNullChecks": true,
"removeComments": true,
"esModuleInterop": true,
"noEmitOnError": true,
"moduleResolution": "node",
"strictPropertyInitialization": true
},
"include": ["./src"]
}