首页 > 其他分享 >JS实现一个布隆过滤器

JS实现一个布隆过滤器

时间:2024-02-18 20:22:58浏览次数:22  
标签:hash 布隆 JS item let 过滤器 const hasFunctions size

之前专门聊过令牌桶算法,而类似的方案还有布隆过滤器。它一般用于高效地查找一个元素是否在一个集合中。
用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的布隆过滤器中,则阻止该请求。

标签:hash,布隆,JS,item,let,过滤器,const,hasFunctions,size
From: https://www.cnblogs.com/freephp/p/18019906

相关文章

  • nvm list available 命令执行异常 Could not retrieve https://npm.taobao.org/mirror
    异常:无法连接镜像地址 解决方法在nvm的安装位置找到文件settings.txt,修改镜像地址修改前 修改后保存再次运行命令 ......
  • 亚马逊云ec2-user安装node-js-18.16.0
    1,下载vnm管理工具curl-o-https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh|bashexportNVM_DIR="$HOME/.nvm"[-s"$NVM_DIR/nvm.sh"]&&\."$NVM_DIR/nvm.sh"#Thisloadsnvm[-s"$NVM_DIR/bash......
  • three.js的物体点击事件
    直接粘贴无脑用 !!!vue文件执行要现在初始化方法里面调用一下onclickS(){   letraycaster=newTHREE.Raycaster();   letmouse=newTHREE.Vector2();     functiononmodelclick(event){    mouse.x=(event.clientX/window.innerWidt......
  • 【c&c++】cJSON详解
    一、JSON概述1.1JSON介绍JSON:JavaScript对象表示法(JavaScriptObjectNotation)。是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似C语音家族的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON......
  • 【总结】HTML+JS逆向混淆混合
    国外的题果然考的与众不同[secrypt_cen.html]这次是HTML网页,然后JS加密判断翻看JS代码很显然,关键的代码在checkPasswordJS混淆是必备的去混淆一条龙走起先将关键代码提取出来 JavaScript function_0x4857(_0x398c7a,_0x2b4590){const_0x104914= _0x25ec(......
  • Vue.js前端框架之vite+vue+naive前端项目模板
    1.搭建Vue示例项目npmcreatevue cdvue-demo:进入项目目录npminstall:安装所有依赖npmrundev:启动项目2.了解Vue开发和工作原理2.1package.json类似于Python项目中pyproject.toml,包含了项目名称、版本、命令、依赖、设定2.2index.html浏览器访问到的HTML文件 ......
  • odoo jsonrpc
    importjsonimportpprintimportrandomimporturllib.requestHOST='192.168.2.21'PORT=8069DB='wywr17'#数据库名称USER=''#登录用户名PASS=''#登录密码defjson_rpc(url,method,params):data={"......
  • VSCOde+Nodejs+Typescript前端开发环境
    1.安装Node.js下载地址:https://nodejs.org/enlts版本:长久稳定版本安装:默认安装就可以了验证:node2.VSCode下载地址:https://code.visualstudio.com/Download安装:默认安装语言切换:安装中文插件,重启 2.1修改终端cmd模式:1.点击设置图标,选择CommandPalette 2.输入:Ter......
  • P1198 [JSOI2008] 最大数
    原题链接题解1:单调栈+并查集?单调栈特性:栈内元素大小和序号由栈底到栈顶具有单调性,本题大小单调减,序号单调增维护:新元素入栈时,栈内剩余的所有小于该元素的元素出栈,并视新元素为集合首领,然后新元素入栈查询:查询集合首领即可code1#definelllonglong#include<bits/stdc++.h>......
  • JSON相关注解的使用
    1.@JsonInclude当使用json进行序列化时,往往会遇到某个实体对象的属性为null,可以使用如下类注解使得属性值为null的时候Java Bean不参与序列化可以作用在类上,也可以作用在字段上@JsonInclude(JsonInclude.Include.NON_NULL)     其他常量值包括:Include.Include.ALWAYS   ......