class BloomFilter {
private size: number;
private storage: Uint8Array;
private numHashes: number;
constructor(size: number, numHashes: number) {
this.size = size;
this.storage = new Uint8Array(size);
this.numHashes = numHashes;
}
private hash(item: string, seed: number): number {
let hash = 0;
for (let i = 0; i < item.length; i++) {
hash = (hash * 33 + item.charCodeAt(i) + seed) & hash;
hash = Math.abs(hash);
}
return hash % this.size;
}
add(item: string): void {
for (let i = 0; i < this.numHashes; i++) {
const position = this.hash(item, i);
this.storage[position] = 1;
}
}
mayContain(item: string): boolean {
for (let i = 0; i < this.numHashes; i++) {
const position = this.hash(item, i);
if (!this.storage[position]) {
return false;
}
}
return true;
}
}
// 使用示例
const filter = new BloomFilter(1000, 5);
filter.add("hello");
console.log(filter.mayContain("hello")); // true
console.log(filter.mayContain("world")); // false