/
linear-probing.js
74 lines (58 loc) · 1.71 KB
/
linear-probing.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
const { hashCodePoly } = require('../utils/hash')
class HashMap {
constructor (size, hashFn = hashCodePoly) {
this.array = new Array(size).fill(null)
this.size = size
this.total = 0
this.X = [-Infinity, -Infinity]
this.hashCode = hashFn
}
searchEmptyIndex (key) {
const intKey = this.hashCode(key)
let index = (intKey % this.size)
while (this.array[index] !== null && this.array[index] !== this.X) {
index = (index + 1) % this.size
}
return index
}
get (key) {
const intKey = this.hashCode(key)
let index = (intKey % this.size)
const init = index
while (this.array[index] !== null) {
if (this.array[index][0] === intKey) {
return this.array[index][1]
}
index = (index + 1) % this.size
if (init === index) {
return
}
}
}
set (key, value) {
if (this.total === this.size) {
throw new Error('Hash table is full')
}
const intKey = this.hashCode(key)
let index = this.searchEmptyIndex(key)
this.array[index] = [intKey, value]
this.total += 1
}
remove (key) {
const intKey = this.hashCode(key)
let index = (intKey % this.size)
const init = index
while (this.array[index]) {
if (this.array[index][0] === intKey) {
this.array[index] = this.X
this.total -= 1
return
}
index = (index + 1) % this.size
if (index === init) {
return
}
}
}
}
module.exports = HashMap