-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashTable.js
125 lines (109 loc) · 2.81 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
class HashTable{
constructor(size){
this.keyMap = new Array(size);
}
////
hash(key){
let total = 0;
const prime = 31;
for(let i = 0; i < Math.min(key.length, 100); i++){
let char = key[i];
let value = char.charCodeAt(0) - 96;
total = (total * prime + value) % this.keyMap.length;
}
return total;
}
////
set(key, value){
const hash = this.hash(key);
if(this.keyMap[hash]){
this.keyMap[hash].push([key, value]);
}else{
this.keyMap[hash] = [[key, value]];
}
return hash +' : '+ this.keyMap[hash];
}
////
get(key){
const hash = this.hash(key);
if(this.keyMap[hash]){
for(let pair of this.keyMap[hash]){
if(pair[0] === key){
return pair[1];
}
}
}
}
////
// return keys in an array
keys(){
let keys = [];
for(let arr of this.keyMap){
if(arr){
arr.forEach(i=>{
keys.push(i[0]);
})
}
}
return keys;
}
////
// return values in an array
values(){
let keys = [];
for(let arr of this.keyMap){
if(arr){
arr.forEach(i=>{
keys.push(i[1]);
})
}
}
return keys;
}
////
// delete a pair by key
delete(key){
const hash = this.hash(key);
if(this.keyMap[hash]){
for(let pair of this.keyMap[hash]){
if(pair[0] === key){
this.keyMap[hash].splice(this.keyMap[hash].indexOf(pair),1);
return pair;
}
}
}
}
////
// update key
updateKey(key, newKey){
const hash = this.hash(key);
if(this.keyMap[hash]){
for(let pair of this.keyMap[hash]){
if(pair[0] === key){
pair[0] = newKey;
}
}
}
}
////
// update value
updateValue(key, newValue){
const hash = this.hash(key);
if(this.keyMap[hash]){
for(let pair of this.keyMap[hash]){
if(pair[0] === key){
pair[1] = newValue;
}
}
}
}
}
let ht = new HashTable(10);
ht.set('pink','#hhh');
ht.set('blue','ggg');
ht.set('red','ddd');
ht.set('cyan','bcs');
ht.set('purple','dsd');
ht.set('salmon','sss');
ht.updateValue('pink', 'fdfdfdfdfdfdfaf');
console.log(ht.values());