Skip to content

Commit 824d068

Browse files
committed
29.01.2019
1 parent 04ae2e2 commit 824d068

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import LinkedList from "./LinkedList";
2+
3+
const tableSize = 32;
4+
5+
class HashTable {
6+
constructor(size = tableSize) {
7+
this.buckets = Array(size)
8+
.fill(null)
9+
.map(() => new LinkedList());
10+
11+
// Map of the keys.
12+
this.keys = {};
13+
}
14+
15+
hash(key) {
16+
return (
17+
Array.from(key).reduce((acc, curr) => acc + curr.charCodeAt(0), 0) %
18+
this.buckets.length
19+
);
20+
}
21+
22+
has(key) {
23+
// Why not this.keys[key] or this.keys.hasOwnProperty?
24+
// --
25+
// this.keys[key] will check on the prototype.
26+
// So if key === "map" this will WRONGLY return true.
27+
// --
28+
// this.keys.hasOwnProperty(key), like the above can still be modifed if a key is named "hasOwnProperty".
29+
return Object.hasOwnProperty(this.keys, key);
30+
}
31+
32+
set(key, value) {
33+
const hash = this.hash(key);
34+
35+
this.keys[key] = hash;
36+
37+
const bucketList = this.buckets[hash];
38+
39+
// Find the node for this key, if it exists.
40+
const node = bucketList.find({
41+
callback: ({ nodeValue }) => nodeValue.key === key
42+
});
43+
44+
if (node) {
45+
// Exists then update the value.
46+
node.value.value = { key, value };
47+
} else {
48+
// Otherwise add it to the list.
49+
bucketList.append({ key, value });
50+
}
51+
}
52+
53+
get(key) {
54+
const hash = this.hash(key);
55+
56+
const bucketList = this.buckets[hash];
57+
58+
const node = bucketList.find({
59+
callback: ({ nodeValue }) => nodeValue.key === key
60+
});
61+
62+
return node ? node.value.value : undefined;
63+
}
64+
}

src/playground/data-structures/LinkedList.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,4 +113,30 @@ class LinkedList {
113113

114114
return this;
115115
}
116+
117+
reverse() {
118+
// Lets reverse the linked list.
119+
let currentNode = this.head;
120+
121+
let prevNode = null;
122+
let nextNode = null;
123+
124+
while (currentNode) {
125+
// This allows it to loop.
126+
nextNode = currentNode.next;
127+
128+
// Now swap the pointer to the opposite direction.
129+
currentNode.next = prevNode;
130+
131+
// Remember the last pointer.
132+
prevNode = currentNode;
133+
// Keep the loop going.
134+
currentNode = nextNode;
135+
}
136+
137+
// The head is the last node turned around.
138+
this.tail = this.head;
139+
140+
this.head = prevNode;
141+
}
116142
}

0 commit comments

Comments
 (0)