散列表是通过hashcde来作为键值对的键值,方便快速的生成和获取。
class HashTable {
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);
}
hashCode(key) {
const tablekey = this.toString(key);
let hash = 5381;
for (let i = 0; i < tablekey.length; i++) {
hash = (hash * 33) + tablekey.charCodeAt(i);
}
return hash % 1013
}
set(key, value) {
if (key != null && value != null) {
const tablekey = this.hashCode(key);
this.table[tablekey] = new ValuePair(key, value);
return true;
}
return false;
}
get(key) {
const valuePair = this.table[this.hashCode(key)];
return valuePair == null ? undefined : valuePair.value;
}
remove(key) {
const hash = this.hashCode(key);
const valuepair = this.table[hash];
if (valuepair != null) {
delete this.table[hash];
return true;
}
return false;
}
}