/
linear_hash_table.js
121 lines (100 loc) · 2.76 KB
/
linear_hash_table.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
const HASH_SIZE = 5;
class Element {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
class LinearHashTable {
constructor () {
this.table = new Array(HASH_SIZE);
this.length = 0;
}
hashCode(key) {
let hash = 0;
for (let i = 0; i < key.length; ++i) {
hash += key.charCodeAt(i);
}
return hash % HASH_SIZE;
};
clear() {
this.table = new Array(HASH_SIZE);
this.length = 0;
};
size () {
return this.length;
};
getBuffer () {
let array = [];
for (let i = 0; i < this.table.length; ++i) {
if(this.table[i]) {
array.push(this.table[i]);
}
}
return array;
};
print () {
for (let i = 0; i < this.table.length; ++i) {
if(this.table[i]) {
console.log(`#${i} -> key: ${this.table[i].key} value: ${this.table[i].value}`);
}
}
};
put (key, value) {
let index = this.hashCode(key);
let startIndex = index;
console.log(`key: ${key} -> index: ${index}`);
do {
if (this.table[index] === undefined) {
this.table[index] = new Element(key, value);
this.length++;
return true;
}
index = (index + 1) % HASH_SIZE;
} while (index !== startIndex);
return false;
};
get(key) {
let index = this.hashCode(key);
let startIndex = index;
do {
if (this.table[index] !== undefined && this.table[index].key === key) {
return this.table[index].value;
}
index = (index + 1) % HASH_SIZE;
} while (index !== startIndex);
return undefined;
}
remove(key) {
let index = this.hashCode(key);
let startIndex = index;
do {
if (this.table[index] !== undefined && this.table[index].key === key) {
let element = this.table[index];
delete this.table[index];
this.length--;
return element;
}
index = (index + 1) % HASH_SIZE;
} while (index !== startIndex);
return undefined;
}
}
let lht = new LinearHashTable();
lht.put("Ana", 172);
lht.put("John", 179);
lht.put("Donnie", 183);
lht.put("Mindy", 190);
lht.put("Paul", 168);
console.log(lht.get("Ana"));
console.log(lht.get("Paul"));
console.log(lht.get("Kim"));
console.log("");
console.log(lht.remove("Ana"));
console.log(lht.get("Paul"));
console.log(lht.remove("Paul"));
console.log(lht.get("Paul"));
console.log(lht.remove("Paul"));
console.log(lht.size());
lht.print();
console.log(lht);