-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hashtable.js
46 lines (36 loc) · 907 Bytes
/
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
class HashTable {
constructor(size){
this.data = new Array(size);
}
_hash(key) {
let hash = 0;
for(let i=0; i < key.length; i++){
hash = (hash + key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
set(key, value) {
let address = this._hash(key);
if(!this.data[address]){
this.data[address] = [];
}
this.data[address].push([key,value]);
return this.data;
}
get(key){
let address = this._hash(key);
let currentBucket = this.data[address];
if(currentBucket){
for(let i=0; i < currentBucket.length; i++){
if(currentBucket[i][0] === key)
return currentBucket[i][1];
}
}
return undefined;
}
}
const myHashTable = new HashTable(50);
myHashTable.set('grapes',10000);
myHashTable.set('grappe',120);
console.log(myHashTable.get('grapes'));
console.log(myHashTable.get('grappe'));