-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashTableCollision.js
72 lines (59 loc) · 1.42 KB
/
hashTableCollision.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
class hashTable{
constructor(size){
this.array=new Array(size)
this.size=size
}
hash(key){
let total=0
for(let i=0;i<key.length;i++){
total+=key.charCodeAt(i)
}return total%this.size
}
setVal(key,value){
let index=this.hash(key)
let bucket=this.array[index]
if(!bucket){
bucket=[[key,value]]
}else{
let sameKey=bucket.find(item=>item[0]===key)
if(sameKey){
sameKey[1]=value
}else{
bucket.push([key,value])
}
}
}
getVal(key){
let index=this.hash(key)
let bucket=this.array[index]
if(bucket){
let sameKey=bucket.find(item=>item[0]===key)
if(sameKey){
return sameKey[1]
}
}else{
return undefined
}
}
remove(key){
let index=this.hash(key)
let bucket=this.array[index]
if(bucket){
let sameKey=bucket.find(item=>item[0]===key)
if(sameKey){
bucket.splice(bucket.indexOf(sameKey),1)
}
}
}
display(){
for(let i=0;i<this.array.length;i++){
if(this.array[i]){
console.log(this.array[i]);
}
}
}
}
let hh=new hashTable(10)
hh.setVal("name","azhar")
hh.setVal("age",23)
hh.display()