Bloom 过滤器(Bloom Filter)是一种用于判断一个元素是否属于一个集合的概率型数据结构。它可以告诉你一个元素可能属于这个集合,或者一定不属于这个集合,但无法确定元素一定属于这个集合(存在一定的误判率)。
以下是一个简单的 JavaScript 实现 Bloom 过滤器的示例:
class BloomFilter {
constructor(size, hashFunctions) {
this.size = size; // 过滤器的大小
this.hashFunctions = hashFunctions; // 哈希函数的数组
this.filter = new Array(size).fill(false); // 初始化一个布尔数组
}
add(item) {
for (const hashFunction of this.hashFunctions) {
const index = hashFunction(item) % this.size;
this.filter[index] = true;
}
}
contains(item) {
for (const hashFunction of this.hashFunctions) {
const index = hashFunction(item) % this.size;
if (!this.filter[index]) {
return false;
}
}
return true;
}
}
// 使用示例
const hashFunctions = [
(item) => {
let hash = 0;
for (let i = 0; i < item.length; i++) {
hash = (hash << 5) + item.charCodeAt(i);
}
return hash;
},
// 可以添加更多的哈希函数
];
const bloomFilter = new BloomFilter(100, hashFunctions);
bloomFilter.add("apple");
bloomFilter.add("orange");
console.log(bloomFilter.contains("apple")); // true
console.log(bloomFilter.contains("banana")); // false (可能误判)
在这个示例中,BloomFilter 类接受一个过滤器的大小和一组哈希函数。add 方法用于添加元素到过滤器中,而 contains 方法用于检查元素是否可能在过滤器中。
注意,Bloom 过滤器有一定的误判率,但它在空间效率和查询速度方面具有优势,特别是在处理大数据集时。根据应用场景的不同,可能需要根据实际情况调整过滤器的大小和哈希函数的数量。