练习
# 练习
要求:
开发一个字典类,字典中会保存键值对的数据
键值对特点:
- 键(key)可以是任何类型,但不允许重复
- 值(value) 可以是任何类型
- 每个键对应一个值
- 所有的键类型相同,所有的值类型相同
字典中对键值对数据的操作:
- 按照键,删除对应的键值对
- 循环每一个键值对
- 得到当前键值对的数量
- 判断某个键是否存在
- 重新设置某个键对应的值,如果不存在,则添加
type Callback<K, V> = (key: K, val: V) => void
export default class Dictionary<K, V> {
private keys: K[] = [];
private vals: V[] = [];
public size: number = 0;
constructor() {
}
set(key: K, val: V) {
if (!key) return false;
const keyIndex = this.getKeyIndex(key);
if (keyIndex === -1) {
this.keys.push(key);
this.vals.push(val);
} else {
this.vals[keyIndex] = val;
}
this.size = this.vals.length;
}
getKeyIndex(key: K): number {
return this.keys.indexOf(key);
}
forEach(cb: Callback<K, V>) {
if (this.size === 0) return;
for (let i = 0; i < this.keys.length; i++) {
cb(this.keys[i], this.vals[i]);
}
}
has(key: K): boolean {
return this.getKeyIndex(key) > -1;
}
delete(key: K): boolean {
const index = this.getKeyIndex(key);
if (index > -1) {
this.keys.splice(index, 1)
this.vals.splice(index, 1)
return true;
}
return false;
}
}