JS实现一个布隆过滤器

之前专门聊过令牌桶算法,而类似的方案还有布隆过滤器。它一般用于高效地查找一个元素是否在一个集合中。

用js实现如下所示:

复制代码
class BloomFilter {
    constructor(size, hashFunctions) {
        this.size = size;
        this.bitArray = new Array(size).fill(0);
        this.hasFunctions = hashFunctions;
    }

    add(item) {
        for (let i = 0; i < this.hasFunctions.length; i++) {
            const index = this.getHash(this.hasFunctions[i], item) % this.size;
            this.bitArray[index] = 1;
        }
    }

    contain(item) {
        for (let i = 0; i < this.hasFunctions.length; i++) {
            const index = this.getHash(this.hasFunctions[i], item) % this.size;
            if (this.bitArray[index] === 0) return false;
        }
        return true;
    }

    getHash(hasFunction, item) {
        return hasFunction(item);
    }

}

const basicHashFunction = (item) => {
    // Transform the item to string
    const chars = String(item);
    let hash = 0;

    // Perform a simple hash calculation on each character in the string
    for (let i = 0; i < chars.length; i++) {
        hash = (hash << 5) + chars.charCodeAt(i); // combination of the bit operations and character ending
        hash = hash & hash;
        hash = Math.abs(hash);
    }
    return hash;
}

const secondHashFunction = (item) => {
    let hash = 0;
    for (let i = 0; i < item.length; i++) {
        const char = item.charCodeAt(i);
        hash = (hash << 5) - hash + char;
    }
    return hash;
}

// usage
const hashFunctions = [basicHashFunction, secondHashFunction];
const bloomFilter = new BloomFilter(1000, hashFunctions);
bloomFilter.add("item01");
bloomFilter.add("item02");
console.log(bloomFilter.contain("item02")); // output: true
console.log(bloomFilter.contain("item02")); // output: false

在上述代码中我们通过多个哈希函数计算元素的哈希值,减少哈希冲突问题。哈希函数还可以用第三方库,不一定非要自己实现,我给出的都是一些简单实现。

布隆过滤器有很多应用场景:

  1. 防止缓存穿透。判断数据是否在缓存中,以免不走缓存。
  2. 优化数据库请求。
  3. 防止恶意访问。如果该请求ip已经在保存恶意IP的布隆过滤器中,则阻止该请求。
相关推荐
xiucai_cs11 天前
布隆过滤器原理与Spring Boot实战
java·spring boot·后端·布隆过滤器
陈振wx:zchen200820 天前
7、如何管理昵称重复?
布隆过滤器·场景题-判重
失散1324 天前
大型微服务项目:听书——11 Redisson分布式布隆过滤器+Redisson分布式锁改造专辑详情接口
分布式·缓存·微服务·架构·布隆过滤器
DARLING Zero two♡3 个月前
C++寻位映射的究极密码:哈希扩展
c++·面试·位图·布隆过滤器
未来影子3 个月前
布隆过滤器和布谷鸟过滤器
过滤器·布隆过滤器·布谷鸟过滤器
smileNicky4 个月前
SpringBoot系列之集成Redisson实现布隆过滤器
java·spring boot·redis·布隆过滤器
dr李四维4 个月前
解决缓存穿透的布隆过滤器与布谷鸟过滤器:谁更适合你的应用场景?
redis·算法·缓存·哈希算法·缓存穿透·布隆过滤器·布谷鸟过滤器
佛祖让我来巡山5 个月前
【快速判断是否存在利器】布隆过滤器和布谷鸟过滤器
布隆过滤器·布谷鸟过滤器
morris1315 个月前
【redis】布隆过滤器的Java实现
java·redis·布隆过滤器
却道天凉_好个秋8 个月前
c++ 位图和布隆过滤器
c++·位图·布隆过滤器