class HashTable {
constructor(bucketSize = 1024) {
this._bucketSize = bucketSize
this._data = new Array(bucketSize)
}
getHashKey(key) {
const h = key
.split('')
.reduce((acc, cur, i) => acc + cur.charCodeAt(0) * (i + 1), 0)
return h % this._bucketSize
}
set(key, value) {
if (typeof key !== 'string') {
key = JSON.stringify(key)
}
const hashKey = this.getHashKey(key)
const bucket = this._data[hashKey]
if (!bucket) {
return (this._data[hashKey] = [[key, value]])
}
const idx = bucket.findIndex(([storedKey]) => key === storedKey)
if (idx === -1) {
return bucket.push([key, value])
}
bucket[idx][1] = value
}
get(key) {
if (typeof key !== 'string') {
key = JSON.stringify(key)
}
const bucket = this._data[this.getHashKey(key)]
if (bucket) {
const data = bucket.find(([storedKey]) => key === storedKey)
return data ? data[1] : undefined
}
return undefined
}
}
const ht = new HashTable()
ht.set({ x: 210 * 2 }, 420)
ht.set({ x: 210 * 2 }, 1)
ht.set([1, 2, 3], 2)
ht.set('cba', 3)
ht.get({ x: 420 }) // 1
ht.get([2, 4, 6].map(x => x / 2)) // 2
ht.get('cba') // 3