-
Notifications
You must be signed in to change notification settings - Fork 94
/
hashtable.js
66 lines (53 loc) · 1.51 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
class HashTable {
constructor(size = 7) {
this.map = new Array(size);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * 23) % this.map.length;
}
return hash;
}
printHashTable() {
for (let i = 0; i < this.map.length; i++) {
console.log(`index ${i}:`, this.map[i]);
}
}
set(key,value) {
let index = this._hash(key);
if(!this.map[index]) this.map[index] = [];
this.map[index].push([key, value]);
return this;
}
get(key) {
let index = this._hash(key);
if(this.map[index]) {
for(let i = 0; i < this.map[index].length; i++) {
if(this.map[index][i][0] === key) {
return this.map[index][i][1];
}
}
}
return undefined;
}
keys() {
let keys = []
for(let i = 0; i < this.map.length; i++) {
if(this.map[i]) {
for(let j = 0; j < this.map[i].length; j++) {
keys.push(this.map[i][j][0]);
}
}
}
return keys;
}
}
let myHashTable = new HashTable();
myHashTable.set("apples", 30);
myHashTable.set("banana", 10);
myHashTable.set("oranges", 75);
myHashTable.set("cherries", 35);
myHashTable.set("avocodo", 60);
console.log(myHashTable.get("oranges"));
console.log( myHashTable.keys() );