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的布隆过滤器中,则阻止该请求。
相关推荐
Aurelius-Shu1 个月前
「数智通识」布隆过滤器:大数据量下的快速存在性判断
大数据·数据结构·算法·哈希算法·布隆过滤器
molashaonian2 个月前
Redis 布隆过滤器性能对比分析
redis·性能测试·布隆过滤器·本地过滤
绝命Coding3 个月前
大厂面试官问我:布隆过滤器有不能扩容和删除的缺陷,有没有可以替代的数据结构呢?【后端八股文二:布隆过滤器八股文合集】
java·redis·后端·springboot·springcloud·guava·布隆过滤器
小呆瓜历险记5 个月前
【数据结构】位图与布隆过滤器
数据结构·位图·哈希表·布隆过滤器
NPE~6 个月前
Golang基于Redis bitmap实现布隆过滤器(完结版)
开发语言·redis·后端·缓存·golang·bitmap·布隆过滤器
林犀居士7 个月前
RedissonClient妙用-分布式布隆过滤器
分布式·redisson·以太坊·布隆过滤器·大数据量去重
皮卡冲撞8 个月前
redis布隆过滤器(Bloom)详细使用教程
redis·哈希算法·散列表·bloom·布隆过滤器
我可以将你更新哟10 个月前
7-爬虫-中间件和下载中间件(加代理,加请求头,加cookie)、scrapy集成selenium、源码去重规则(布隆过滤器)、分布式爬虫
爬虫·scrapy·中间件·分布式爬虫·布隆过滤器
RedMapleGI1 年前
Redis基于布隆过滤器解决缓存穿透问题(15)
redis·缓存穿透·布隆过滤器·1024程序员节·bloom filter