-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSA_HT_New
More file actions
57 lines (50 loc) · 1.35 KB
/
DSA_HT_New
File metadata and controls
57 lines (50 loc) · 1.35 KB
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
class HashTable {
constructor(size = 7) {
this.dataMap = new Array(size);
}
_hash(key) {
let hash = 0;
for ( let i = 0; i < key.length; i++ ) {
hash = ( hash + key.charCodeAt(i) * 23 ) % this.dataMap.length;
}
return hash;
}
set(key, value) {
let index = this._hash(key);
if ( !this.dataMap[index] ) {
this.dataMap[index] = [];
}
this.dataMap[index].push([key, value]);
return this;
}
get(key) {
const index = this._hash(key);
if ( index >= this.dataMap.length ) return undefined;
if ( !this.dataMap[index] ) return undefined;
for ( let i = 0; i < this.dataMap[index].length; i++ ) {
if ( this.dataMap[index][i][0] === key ) return this.dataMap[index][i][1];
}
return undefined;
}
keySet() {
let allKeys = [];
this.dataMap.forEach(element => {
if ( element.length > 0 ) {
element.forEach(entry => {
allKeys.push(entry[0]);
});
}
});
return allKeys;
}
}
function test() {
let ht = new HashTable();
ht.set('bolts', 1400);
ht.set('washers', 50);
ht.set('lumber', 10);
ht.get('lumber');
console.log(ht.keySet());
console.log(ht);
}
test();