JavaScript实现字典类
字典也称为映射、符号表或关联数组,在计算机科学中经常用来保存对象的引用地址。
集合以【值,值】的形式存放元素,字典是以【键,值】的形式存放元素。
class ValuePair { //存放一对键值的对象
constructor(key, value) {
this.key = key;
this.value = value;
}
toString() {
return `[#${this.key}:${this.value}]`;
}
}
class Dictionary {
constructor() {
this.table = {};
}
toStrFn(str) {
if (str == null) {
return 'null';
} else if (str === undefined) {
return "undefined";
} else {
return str.toString();
}
}
remove(key) {
if (!this.hasKey(key)) {
return false;
}
delete this.table[this.toStrFn(key)];
return true;
}
hasKey(key) {
return this.table[this.toStrFn(key)] != null;
}
set(key, value) {
if (key == null || value == null) {
return false;
}
const tableKey = this.toStrFn(key);
this.table[tableKey] = new ValuePair(key, value);
return true;
}
get(key) {
if (!this.hasKey(key)) {
return undefined;
}
return this.table[this.toStrFn(key)]; //返回值是键值对
}
clear() {
this.table = {};
}
size() {
return Object.keys(this.table).length;
}
isEmpty() {
return this.size() === 0;
}
keys() {
return this.keyValues().map(valuePair => valuePair.key);
}
values() {
return this.keyValues().map(valuePair => valuePair.value);
}
keyValues() {
return Object.values(this.table);
}
forEach(callBackFn) {
const valuePair = this.keyValues();
for (let i = 0; i < valuePair.length; i++) {
callBackFn(valuePair[i].key, valuePair[i].value);
}
}
toString() {
if (this.isEmpty()) {
return "";
}
const valuePair = this.keyValues();
let objString = valuePair[0].toString();
for (let i = 1; i < valuePair.length; i++) {
objString = `${objString},${valuePair[i].toString()}`;
}
return objString;
}
}
const dictionary = new Dictionary();
dictionary.set('Gandalf', 'gandalf@email.com');
dictionary.set('John', 'johnsnow@email.com');
dictionary.set('Tyrion', 'tyrion@email.com');
console.log(dictionary.hasKey('Gandalf')); // true
console.log(dictionary.size()); // 3
console.log(dictionary.keys()); // ["Gandalf", "John", "Tyrion"]
console.log(dictionary.values()); // ["gandalf@email.com", "johnsnow@email.com", "tyrion@email.com"]
console.log(dictionary.get('Tyrion')); // tyrion@email.com
dictionary.remove('John');
console.log(dictionary.keys()); // ["Gandalf", "Tyrion"]
console.log(dictionary.values()); // ["gandalf@email.com", "tyrion@email.com"]
console.log(dictionary.keyValues()); // [{key: "Gandalf", value: "gandalf@email.com"}, {key: "Tyrion", value: "tyrion@email.com"}]
console.log(dictionary.toString()); // [#Gandalf: gandalf@email.com],[#Tyrion: tyrion@email.com]
dictionary.forEach((k, v) => {
console.log('forEach: ', `key: ${k}, value: ${v}`);
});
// forEach: key: Gandalf, value: gandalf@email.com
// forEach: key: Tyrion, value: tyrion@email.com

浙公网安备 33010602011771号