Skip to content

Commit a938442

Browse files
committed
add HashTable
1 parent 7659b06 commit a938442

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

Other data structures/HashTable.html

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Title</title>
6+
</head>
7+
<body>
8+
<script>
9+
class HashTable {
10+
constructor(M) {
11+
this.hashTable = Array(M);
12+
this.M = M;
13+
this.size = 0;
14+
for (let i = 0; i < M; i++) {
15+
this.hashTable[i] = new Map()
16+
}
17+
}
18+
19+
add(key, value) {
20+
let map = this.hashTable[this.hash(key)];
21+
if (map.has(key)) {
22+
map.set(key, value)
23+
} else {
24+
map.set(key, value);
25+
this.size++;
26+
}
27+
}
28+
29+
remove(key) {
30+
let map = this.hashTable[this.hash(key)],
31+
ret = null;
32+
if (map.has(key)) {
33+
ret = map.delete(key);
34+
this.size--
35+
}
36+
return ret
37+
}
38+
39+
set(key, value) {
40+
let map = this.hashTable[this.hash(key)];
41+
if(!map.has(key)){
42+
throw new Error(`${key} doesn't exist!`)
43+
}
44+
map.set(key, value)
45+
}
46+
47+
hash(key) {
48+
let str = null;
49+
switch (this._type(key)) {
50+
case 'string':
51+
str = key;
52+
break;
53+
case 'null':
54+
case 'undefined':
55+
case 'number':
56+
case 'boolean':
57+
str = key + ''
58+
}
59+
60+
return (this._hashCode(str) & 0x7fffffff) % this.M
61+
}
62+
63+
contains(key) {
64+
return this.hashTable[this.hash(key)].has(key)
65+
}
66+
67+
get(key){
68+
return this.hashTable[this.hash(key)].get(key)
69+
}
70+
71+
_type(key) {
72+
let str = Object.prototype.toString.call(key),
73+
type = str.slice(8, -1).toLowerCase();
74+
75+
return type
76+
}
77+
78+
//辅助函数
79+
_hashCode(str) {
80+
let h = 0, off = 0;
81+
let len = str.length;
82+
for (let i = 0; i < len; i++) {
83+
h = 31 * h + str.charCodeAt(off++);
84+
}
85+
let t = -2147483648 * 2;
86+
while (h > 2147483647) {
87+
h += t
88+
}
89+
return h
90+
}
91+
}
92+
</script>
93+
</body>
94+
</html>

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy