-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashTable.js
60 lines (54 loc) · 1.46 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
class HashTable {
constructor(size) {
this.size = size
this.data = new Array(size);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
return hash % this.size;
}
set(key, value) {
let hash = this._hash(key);
let current = this.data[hash];
if(current) {
for (let i =0; i<current.length; i++) {
if (current[i][0] == key) {
current[i][1] = value;
return;
}
}
current.push([key,value]);
} else {
this.data[hash] = [];
this.data[hash].push([key, value]);
}
return this.data;
}
get(key) {
let hash = this._hash(key);
if (this.data[hash]) {
for (let i=0; i < this.data[hash].length; i++ ) {
if (this.data[hash][i][0] == key) {
return this.data[hash][i][1];
}
}
}
return undefined;
}
remove(key) {
let hash = this._hash(key);
if (this.data[hash]) {
for (let i=0; i < this.data[hash].length; i++ ) {
if (this.data[hash][i][0] == key) {
this.data[hash].splice(i, 1);
return true
}
}
}
return false;
}
}
const myHashTable = new HashTable(50)