-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashTable.js
39 lines (37 loc) · 1.02 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
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;
}
return this.data[address].push([key, value]);
}
get(key){
let address = this._hash(key);
let currentBucket = this.data[address];
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.get('grapes')
myHashTable.set('apples', 9)
// myHashTable.get('apples')
console.log(myHashTable.get('apples'))