-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathHashSet.js
More file actions
113 lines (98 loc) · 2.99 KB
/
HashSet.js
File metadata and controls
113 lines (98 loc) · 2.99 KB
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
/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.
* Use is of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
import standardHashCodeFunction from "../utils/standardHashCodeFunction.js";
import standardEqualsFunction from "../utils/standardEqualsFunction.js";
import arrayToString from "../utils/arrayToString.js";
let DEFAULT_LOAD_FACTOR = 0.75;
let INITIAL_CAPACITY = 16
export default class HashSet {
constructor(hashFunction, equalsFunction) {
this.buckets = new Array(INITIAL_CAPACITY);
this.threshold = Math.floor(INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
this.itemCount = 0;
this.hashFunction = hashFunction || standardHashCodeFunction;
this.equalsFunction = equalsFunction || standardEqualsFunction;
}
get(value) {
if(value == null) {
return value;
}
let bucket = this._getBucket(value)
if (!bucket) {
return null;
}
for (let e of bucket) {
if (this.equalsFunction(e, value)) {
return e;
}
}
return null;
}
add(value) {
let existing = this.getOrAdd(value);
return existing === value;
}
getOrAdd(value) {
this._expand();
let slot = this._getSlot(value);
let bucket = this.buckets[slot];
if (!bucket) {
bucket = [value];
this.buckets[slot] = bucket;
this.itemCount++;
return value;
}
for (let existing of bucket) {
if (this.equalsFunction(existing, value)) {
return existing;
}
}
bucket.push(value);
this.itemCount++;
return value;
}
has(value) {
return this.get(value) != null;
}
values() {
return this.buckets.filter(b => b != null).flat(1);
}
toString() {
return arrayToString(this.values());
}
get length() {
return this.itemCount;
}
_getSlot(value) {
let hash = this.hashFunction(value);
return hash & this.buckets.length - 1;
}
_getBucket(value) {
return this.buckets[this._getSlot(value)];
}
_expand() {
if (this.itemCount <= this.threshold) {
return;
}
let old_buckets = this.buckets;
let newCapacity = this.buckets.length * 2;
this.buckets = new Array(newCapacity);
this.threshold = Math.floor(newCapacity * DEFAULT_LOAD_FACTOR);
for (let bucket of old_buckets) {
if (!bucket) {
continue;
}
for (let o of bucket) {
let slot = this._getSlot(o);
let newBucket = this.buckets[slot];
if (!newBucket) {
newBucket = [];
this.buckets[slot] = newBucket;
}
newBucket.push(o);
}
}
}
}