Skip to content

Commit 8e33980

Browse files
committed
update: added BloomFilters
1 parent ec38f2e commit 8e33980

File tree

1 file changed

+97
-0
lines changed
  • src/_DataStructures_/BloomFilters

1 file changed

+97
-0
lines changed
+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
class BloomFilters {
2+
constructor(size = 101) {
3+
this.size = size;
4+
this.data = this.getStorage(size);
5+
}
6+
7+
add(element) {
8+
const indices = this.getIndices(element);
9+
10+
for (let i = 0; i < indices.length; i += 1) {
11+
this.data.setBit(indices[i]);
12+
}
13+
}
14+
15+
contains(element) {
16+
const indices = this.getIndices(element);
17+
18+
for (let i = 0; i < indices.length; i += 1) {
19+
const index = indices[i];
20+
if (!this.data.getBit(index)) {
21+
return false; // item is definately not there
22+
}
23+
}
24+
return true; // item may be there
25+
}
26+
27+
getIndices(element) {
28+
return [this.hashOne(element), this.hashTwo(element), this.hashThree(element)];
29+
}
30+
31+
hashOne(value) {
32+
const stringValue = String(value);
33+
let hashVal = 0;
34+
35+
for (let i = 0; i < stringValue.length; i += 1) {
36+
hashVal += stringValue.charCodeAt(i) - 96;
37+
}
38+
39+
// eslint-disable-next-line no-bitwise
40+
hashVal &= hashVal;
41+
42+
return Math.abs(hashVal % this.size);
43+
}
44+
45+
hashTwo(value) {
46+
const stringValue = String(value);
47+
const PRIME_MULTIPLIER = 1801; // Random prime number
48+
let hashVal = 0;
49+
50+
for (let i = 0; i < stringValue.length; i += 1) {
51+
hashVal += stringValue.charCodeAt(i) - 96;
52+
hashVal *= PRIME_MULTIPLIER;
53+
}
54+
55+
return Math.abs(hashVal % this.size);
56+
}
57+
58+
hashThree(value) {
59+
const stringValue = String(value);
60+
const PRIME_MULTIPLIER = 1801; // Random prime number
61+
const PRIME_ADDER = 2029; // Random prime number
62+
let hashVal = 0;
63+
64+
for (let i = 0; i < stringValue.length; i += 1) {
65+
hashVal += stringValue.charCodeAt(i) - 96;
66+
hashVal *= PRIME_MULTIPLIER;
67+
hashVal += PRIME_ADDER;
68+
}
69+
// eslint-disable-next-line no-bitwise
70+
hashVal &= hashVal;
71+
return Math.abs(hashVal % this.size);
72+
}
73+
74+
// eslint-disable-next-line class-methods-use-this
75+
getStorage(size) {
76+
const data = new Array(size).fill(0);
77+
78+
return {
79+
setBit(index) {
80+
data[index] = 1;
81+
},
82+
getBit(index) {
83+
return data[index];
84+
},
85+
};
86+
}
87+
}
88+
89+
// const b = new BloomFilters();
90+
91+
// b.add('React.js');
92+
// b.add('Node.js');
93+
94+
// console.log(b.contains('JavaScript'));
95+
// console.log(b.contains('React.js'));
96+
97+
module.exports = BloomFilters;

0 commit comments

Comments
 (0)