Skip to content

Instantly share code, notes, and snippets.

@francisrstokes
Last active May 31, 2018 17:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francisrstokes/82cdcb29c79cc9ef6eac50597cfd2c19 to your computer and use it in GitHub Desktop.
Save francisrstokes/82cdcb29c79cc9ef6eac50597cfd2c19 to your computer and use it in GitHub Desktop.
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;
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;
}
}
}
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