-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.js
70 lines (61 loc) · 1.42 KB
/
hashtable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* @title: Hashtable
* @description: Simple HashTable
* @author: Thorsten Kober
* @email: [email protected]
*/
class Dictionary {
constructor() {
this.data = {};
}
set(key, value) {
this.data[key] = value;
}
get(key) {
return this.data[key];
}
}
class HashTable {
constructor(size = 1000) {
this.size = size;
this.slots = [];
for (let i = 0; i < this.size; i++) {
this.slots[i] = new Dictionary();
}
}
getSlotIndex(key) {
return HashTable.hash(key) % this.size;
}
getSlot(key) {
return this.slots[this.getSlotIndex(key)];
}
set(key, value) {
this.getSlot(key).set(key, value);
}
get(key) {
return this.getSlot(key).get(key);
}
static hash(key) {
let hash = 0;
if (key.length === 0) return hash;
for (let i = 0; i < key.length; i++) {
// hash = (hash * 32) - hash
// left bitwise shift
hash = (hash << 5) - hash; // eslint-disable-line
hash += key.charCodeAt(i);
// ensures 32 bit unsigned integer
hash &= hash; // eslint-disable-line
// hash = hash & hash
}
return hash;
}
}
// npx jest datastructures/hashtable/hashtable.js
describe('hashtable data structure', () => {
it('should return correct value when retrieving', () => {
const hashTable = new HashTable();
hashTable.set('one', 1);
hashTable.set('two', 2);
expect(hashTable.get('one')).toBe(1);
});
});