字典数据结构,由键值对组成。
class ValuePair {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
class Dictionary {
table = {}
toString(item) {
if (item === null) {
return 'null';
} else if (item === undefined) {
return 'undefined';
} else if (typeof item === 'string' || item instanceof String) {
return item;
}
return JSON.stringify(item);
}
hasKey(key) {
return this.table[this.toString(key)] != null;
}
set(key, value) {
if (key != null && value != null) {
const tablekey = this.toString(key);
console.log(tablekey);
this.table[tablekey] = new ValuePair(key, value);
return true;
}
return false;
}
get(key) {
const valuepair = this.table[this.toString(key)];
return valuepair == null ? undefined : valuepair.value;
}
remove(key) {
if (this.hasKey(key)) {
delete this.table[this.toString(key)];
return true;
}
return false;
}
keys() {
return this.keyValues().map(item => item.key);
}
values() {
return this.keyValues().map(item => item.value);
}
keyValues() {
return Object.values(this.table);
}
size() {
return Object.keys(this.table).length;
}
isEmpty() {
this.size() === 0;
}
clear() {
this.table = {};
}
forEach(callback) {
const valuepair = this.keyValues();
for (let i = 0; i < valuepair.length; i++) {
callback(valuepair[i].key,valuepair[i].value);
}
}
}