Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ae5ea99

Browse files
committed
update: added rehashing to avoid collision
1 parent bd73d1f commit ae5ea99

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

‎src/_DataStructures_/HashTable/index.js‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@ const HashEntry = require('./HashEntry');
33
class HashTable {
44
constructor(slots) {
55
// init with a default set of slots
6-
this.slot = slots || 17;
6+
this.slot = slots || 19;
77
// size to hold the current size
88
// and help to resize when the table is half filled
99
this.size = 0;
10+
// threshold (let it be 70%)
11+
this.threshold = 0.7;
1012
// the main bucket
1113
this.bucket = new Array(this.slot);
1214

@@ -32,6 +34,34 @@ class HashTable {
3234
return index;
3335
}
3436

37+
_resize() {
38+
const oldSlot = this.slot;
39+
const oldBucket = this.bucket;
40+
41+
this.slot = oldSlot * 2;
42+
const newBucket = new Array(this.slot);
43+
// fill the new bucket with nulls
44+
for (let i = 0; i < this.slot; i += 1) newBucket[i] = null;
45+
46+
this.bucket = newBucket;
47+
48+
for (let i = 0; i < oldSlot; i += 1) {
49+
if (oldBucket[i]) {
50+
// get all the nodes associated here
51+
let head = oldBucket[i];
52+
53+
while (head !== null) {
54+
const { key, value } = head;
55+
// eslint-disable-next-line no-underscore-dangle
56+
const newIndex = this._hash(key);
57+
// eslint-disable-next-line no-underscore-dangle
58+
this._push(newIndex, { key, value });
59+
head = head.next;
60+
}
61+
}
62+
}
63+
}
64+
3565
_push(index, value) {
3666
/**
3767
* Util to add a SSL to the index in case of more than once
@@ -76,6 +106,17 @@ class HashTable {
76106
// storing value as an key-value pair
77107
// eslint-disable-next-line no-underscore-dangle
78108
this._push(index, { key, value });
109+
110+
/**
111+
* calculate the load factor, if it's greater than threshold
112+
* resize the hash table
113+
*/
114+
const loadFactor = (this.size / this.slot).toFixed(1);
115+
if (loadFactor > this.threshold) {
116+
// console.log('Resizing hash table');
117+
// eslint-disable-next-line no-underscore-dangle
118+
this._resize();
119+
}
79120
}
80121

81122
get(key) {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /