-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhash.js
More file actions
44 lines (39 loc) · 857 Bytes
/
hash.js
File metadata and controls
44 lines (39 loc) · 857 Bytes
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
class HashTable{
constructor(){
this.items = []
}
get(key){
const hash = this.keyToHash(key)
return this.items[hash]
}
set(key,value){
const hash = this.keyToHash(key)
this.items[hash] = value
}
remove(key){
const hash = this.keyToHash(key)
delete this.items[hash]
}
keyToHash(key){
// 把字符串key,变成数字
let hash = 0
for(let i=0;i<key.length;i++){
hash += key.charCodeAt(i)
}
hash = hash%37 // 这个数字要随时变
// 数字会在37以内
return hash
}
log(){
console.log(this.items)
}
}
let kkb = new HashTable()
kkb.set('name','kaikeba')
kkb.set('bestTeacher','大圣老师')
console.log(kkb.get('name'))
console.log(kkb.get('bestTeacher'))
// kkb.remove('name')
console.log(kkb.get('name'))
kkb.log()
// 不同的key 算出的hash一样