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的布隆过滤器中,则阻止该请求。
相关推荐
佛祖让我来巡山2 天前
Redis布隆过滤器的保姆级教程
布隆过滤器
佛祖让我来巡山8 天前
Redis快速实现布隆过滤器:缓存去重的“智能门卫”
布隆过滤器
爱敲代码的TOM18 天前
详解布隆过滤器及其实战案例
redis·布隆过滤器
蜂蜜黄油呀土豆1 个月前
Redis 高并发场景与数据一致性问题深度解析
redis·分布式锁·秒杀系统·数据一致性·布隆过滤器
佛祖让我来巡山3 个月前
布谷鸟过滤器详解:从原理到Spring Boot实战
布隆过滤器·布谷鸟过滤器
佛祖让我来巡山3 个月前
布隆过滤器的完整最佳实践案例
布隆过滤器
JanelSirry3 个月前
真实场景:防止缓存穿透 —— 使用 Redisson 布隆过滤器
数据库·mysql·缓存·redisson·布隆过滤器
xiucai_cs6 个月前
布隆过滤器原理与Spring Boot实战
java·spring boot·后端·布隆过滤器
陈振wx:zchen20086 个月前
7、如何管理昵称重复?
布隆过滤器·场景题-判重
失散136 个月前
大型微服务项目:听书——11 Redisson分布式布隆过滤器+Redisson分布式锁改造专辑详情接口
分布式·缓存·微服务·架构·布隆过滤器