-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashSet.js
146 lines (115 loc) · 2.74 KB
/
HashSet.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
136
137
138
139
140
141
142
143
144
145
146
class HashSet {
constructor(capacity = 16, loadFactor = 0.8) {
this.buckets = [];
this.entries = 0;
this.capacity = capacity;
this.loadFactor = loadFactor;
}
hash(key) {
let hashCode = 0;
const primeNumber = 31;
for (let i = 0; i < key.length; i++) {
hashCode = (hashCode * primeNumber + key.charCodeAt(i)) % 16;
}
return hashCode;
}
addEntry() {
this.entries += 1;
if (Math.ceil(this.capacity * this.loadFactor) < this.entries) {
this.capacity *= 2;
}
}
removeEntry() {
this.entries -= 1;
}
set(key, value) {
const index = this.hash(key);
const nodeValue = key;
if (!this.buckets[index]) {
const list = new LinkedList();
list.append(nodeValue);
this.buckets[index] = list;
this.addEntry();
return;
}
if (this.has(key)) {
this.buckets[index].list.forEach((node, i) => {
if (Object.keys(node.value) === key) {
this.buckets[index].delete(i);
this.buckets[index].insert(
new Node(nodeValue, this.buckets[index].list[i]?.nextNode || null),
i
);
return;
}
});
return;
}
this.buckets[index].append(nodeValue);
this.addEntry();
}
get(key) {
const index = this.hash(key);
this.bucketIndexCheck(index);
const bucket = this.buckets[this.hash(key)];
for (i = 0; i < bucket.length; i++) {
if (bucket[i].value === key) {
return bucket[i].value;
}
}
return null;
}
has(key) {
const bucket = this.buckets[this.hash(key)];
if (bucket) {
for (let i = 0; i < bucket.list.length; i++) {
if (bucket.list[i].value === key) {
return true;
}
}
}
return false;
}
remove(key) {
const index = this.hash(key);
const isThereElement = false;
const bucket = this.buckets[index];
if (bucket.size === 1 || bucket.size === 0) {
this.buckets[index] = undefined;
this.removeEntry();
}
for (i = 0; i < bucket.length; i++) {
if (bucket[i].value === key) {
this.buckets[index].delete(i);
this.removeEntry();
isThereElement = true;
}
}
return isThereElement;
}
length() {
return this.entries;
}
clear() {
this.buckets = [];
this.entries = 0;
this.capacity = 0;
}
keys() {
return this.entry().map((ent) => ent[0]);
}
values() {
return this.entry().map((entry) => entry[1]);
}
entry() {
const entriesList = [];
this.buckets.forEach((bucket) => {
if (!!bucket.size) {
bucket.list.forEach((node) => {
entriesList.push(...Object.entries(node.value));
});
}
});
return entriesList;
}
}