-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash-set.mjs
132 lines (107 loc) · 2.75 KB
/
hash-set.mjs
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
import LinkedList from "./linked-list.mjs";
class HashSet {
constructor() {
this.capacity = 16;
this.loadFactor = 0.75;
this.buckets = Array.from(Array(this.capacity));
this.entries = 0;
}
hash(key) {
let hashCode = 0;
const primeNumber = 31;
for (let i = 0; i < key.length; i++) {
hashCode = (primeNumber * hashCode + key.charCodeAt(i)) % this.capacity;
}
return hashCode;
}
set(key) {
const hashCodeIndex = this.hash(key);
if (hashCodeIndex < 0 || hashCodeIndex >= this.capacity) {
throw new Error("Trying to access index out of bound");
}
if (this.buckets[hashCodeIndex]) {
const list = this.buckets[hashCodeIndex];
const entry = list.search(key);
if (entry) {
return;
} else {
list.append(key);
}
} else {
const list = new LinkedList();
list.append(key);
this.buckets[hashCodeIndex] = list;
}
this.entries++;
if (this.entries > this.capacity * this.loadFactor) {
this.growBuckets();
}
}
get(key) {
const hashCodeIndex = this.hash(key);
if (hashCodeIndex < 0 || hashCodeIndex >= this.capacity) {
throw new Error("Trying to access index out of bound");
}
if (this.buckets[hashCodeIndex]) {
const list = this.buckets[hashCodeIndex];
const entry = list.search(key);
if (entry) {
return entry.key;
}
}
return null;
}
has(key) {
const hashCodeIndex = this.hash(key);
if (hashCodeIndex < 0 || hashCodeIndex >= this.capacity) {
throw new Error("Trying to access index out of bound");
}
if (this.buckets[hashCodeIndex]) {
const list = this.buckets[hashCodeIndex];
return list.contains(key);
}
return false;
}
remove(key) {
const hashCodeIndex = this.hash(key);
if (hashCodeIndex < 0 || hashCodeIndex >= this.capacity) {
throw new Error("Trying to access index out of bound");
}
const list = this.buckets[hashCodeIndex];
if (list) {
const hasRemoved = list.remove(key);
if (hasRemoved) {
this.entries--;
return true;
}
}
return false;
}
length() {
return this.entries;
}
clear() {
this.capacity = 16;
this.buckets = Array.from(Array(this.capacity));
this.entries = 0;
}
keys() {
const keysArray = [];
this.buckets.forEach((bucket) => {
if (bucket) {
keysArray.push(...bucket.getListData("key"));
}
});
return keysArray;
}
growBuckets() {
const currentKeys = this.keys();
this.capacity = this.capacity * 2;
this.buckets = Array.from(Array(this.capacity));
this.entries = 0;
currentKeys.forEach((key) => {
this.set(key);
});
}
}
export default HashSet;