Last active
May 31, 2018 17:34
-
-
Save francisrstokes/82cdcb29c79cc9ef6eac50597cfd2c19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HashTable { | |
constructor(bucketSize = 1024) { | |
this._bucketSize = bucketSize; | |
this._data = new Array(bucketSize); | |
} | |
hashKey(key) { | |
const h = JSON.stringify(key, Object.keys(key).sort()) | |
.split('') | |
.reduce((acc, cur, i) => acc + cur.charCodeAt(0) * (i+1), 0); | |
return h % this._bucketSize; | |
} | |
set(key, value) { | |
return this._data[this.hashKey(key)] = value; | |
} | |
get(key) { | |
return this._data[this.hashKey(key)]; | |
} | |
} | |
module.exports = HashTable; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ConflictResolvingHashTable { | |
constructor(bucketSize = 1024) { | |
this._bucketSize = bucketSize; | |
this._data = new Array(bucketSize); | |
} | |
hashKey(key) { | |
const h = JSON.stringify(key, Object.keys(key).sort()) | |
.split('') | |
.reduce((acc, cur, i) => acc + cur.charCodeAt(0) * (i+1), 0); | |
return h % this._bucketSize; | |
} | |
set(key, value) { | |
const hk = this.hashKey(key); | |
const bucket = this._data[hk]; | |
if (Array.isArray(bucket)) { | |
const idx = bucket.findIndex(([storedKey]) => key === storedKey); | |
if (idx === -1) { | |
bucket.push([key, value]); | |
} else { | |
bucket[idx][1] = value; | |
} | |
} else { | |
this._data[hk] = [[key, value]]; | |
} | |
} | |
get(key) { | |
const bucket = this._data[this.hashKey(key)]; | |
if (Array.isArray(bucket)) { | |
const keyValue = bucket.find(([storedKey]) => key === storedKey); | |
return keyValue ? keyValue[1] : undefined; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const HashTable = require('./HashTable.js'); | |
// Create a hashtable with 2048 buckets (unique slots) | |
const ht = new HashTable(2048); | |
// Keys can most javascript primitives | |
ht.set({ x: 210 * 2}, 1); | |
ht.set([1,2,3], 2); | |
ht.set('cba', 3); | |
// Retrieving doesn't require references - deeply equivilent structures will hash to the same value | |
const values = [ | |
ht.get({x: 420}), // 1 | |
ht.get([2,4,6].map(x => x / 2)), // 2 | |
ht.get('cba'), // 3 | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment