Bloom Filter Probabilistic Membership (JavaScript)
Implement a bloom filter with k hash functions for probabilistic membership testing with a configurable false positive rate.
Code
class BloomFilter {
constructor(size = 1000, k = 7) {
this.bits = new Uint8Array(size);
this.size = size;
this.k = k;
}
hash(str, seed) {
let h = seed;
for (let i = 0; i < str.length; i++) {
h = (h * 31 + str.charCodeAt(i)) % this.size;
}
return h;
}
add(item) {
const s = String(item);
for (let i = 0; i < this.k; i++) this.bits[this.hash(s, i + 1)] = 1;
}
contains(item) {
const s = String(item);
for (let i = 0; i < this.k; i++) if (!this.bits[this.hash(s, i + 1)]) return false;
return true;
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.