-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudo-hash-table.js
136 lines (120 loc) · 3.37 KB
/
sudo-hash-table.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class HashTable{
constructor(size = 100){
this.table = new Array(size);
}
computeHash(string){
let H = this.findPrime(this.table.length);
let total = 0;
for(let i = 0; i < string.length ; ++i){
total += H * total + string.charCodeAt(i);
}
return total % this.table.length;
}
put(item){
let key = this.computeHash(item)
return !this.table[key] ? this.table[key] = item : false;
}
remove(item){
let key = this.computeHash(item)
return this.table[key] = undefined;
}
search(item){
let key = this.computeHash(item);
return this.table[key] === item;
}
size(){
let counter = 0;
for (let i = 0, len = this.table.length; i < len; i++){
if(this.table[i]){
counter++;
}
return counter;
}
}
isEmpty(){
for(let i =0, len = this.table.length; i < len; i++){
if(this.table[i]){
return false;
}
return true;
}
}
}
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
class HashTableWithChaining{
constructor(size = 10){
this.table = new Array(size);
}
put(item){
let key = this.computeHash(item);
let node = new Node(item);
if(this.table[key]){
node.next = this.table[key];
}
this.table[key] = node;
}
remove(item){
let key = this.computeHash(item)
if(this.table[key]){
if(this.table[key].data === item){
this.table[key] = this.table[key].next;
} else {
let current = this.table[key].next;
let prev = this.table[key];
while(current){
if(current.data == item){
prev.next = current.next;
}
prev = current;
current = current.next;
}
}
}
}
contains(item){
for(let i = 0; i < this.table.length; i++){
if(this.table[i]){
let current = this.table[i];
while(current){
if(current.data === item){
return true;
}
current = current.next;
}
}
}
return false;
}
size(item){
let counter = 0;
for(let i = 0; i < this.table.length; i++){
if(this.table[i]){
let current = this.table[i];
while(current){
counter++;
current = current.next;
}
}
}
return counter;
}
isEmpty(){
return this.size()<1;
}
traverse(fn){
for(let i=0; i<this.table.length; i++){
if(this.table[i]){
let current = this.table[i];
while(current){
fn(current);
current = current.next;
}
}
}
}
}