typescript 布隆过滤器实现

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
posted @ 2023-09-13 11:11  林余  阅读(10)  评论(0编辑  收藏  举报