-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinearHashing.js
46 lines (46 loc) · 1.33 KB
/
LinearHashing.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
class LinearHashing {
// key.isDeleted is true is key is null
constructor(tableSize = 11) {
this.tableSize = tableSize
this.hashTable = new Array(tableSize)
}
hashFunction(key, order) {
return (key + order) % this.tableSize
}
insert(key) {
key = parseInt(key)
if (isNaN(key))
throw "Invalid Key!"
for (let i = 0; i < this.tableSize; ++i) {
let hashedKey = this.hashFunction(key, i)
switch (this.hashTable[hashedKey]) {
case undefined:
case null:
this.hashTable[hashedKey] = key
return hashedKey
case key:
throw "Duplicate Key!"
}
}
throw "Overflow!"
}
search(key) {
key = parseInt(key)
if (isNaN(key))
throw "Invalid Key!"
for (let i = 0; i < this.tableSize; ++i) {
let hashedKey = this.hashFunction(key, i)
switch (this.hashTable[hashedKey]) {
case undefined:
throw "Key Not Found!"
case key:
return hashedKey
}
}
}
delete(key) {
let hashedKey = this.search(key)
this.hashTable[hashedKey] = null
return hashedKey
}
}