Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Bloom filter implementation in JavaScript
- class BloomFilter {
- constructor(size) {
- this.array = new Array(size).fill(0);
- this.indexes = [];
- }
- hash(string) {
- let hash = 0;
- for (let i = 0; i < string.length; i++) {
- const char = string.charCodeAt(i);
- hash = (hash << 5) - hash + char;
- hash &= hash;
- }
- return hash;
- }
- getIndexes(string) {
- const hash1 = Math.abs(this.hash(string)) % this.array.length;
- const hash2 = Math.abs(this.hash(string + '1')) % this.array.length;
- return [hash1, hash2];
- }
- add(string) {
- this.indexes = this.getIndexes(string);
- for (let i = 0; i < this.indexes.length; i++) {
- const index = this.indexes[i];
- this.array[index] = 1;
- }
- }
- contains(string) {
- this.indexes = this.getIndexes(string);
- for (let i = 0; i < this.indexes.length; i++) {
- const index = this.indexes[i];
- if (this.array[index] === 0) {
- return false;
- }
- }
- return true;
- }
- export() {
- return this.array;
- }
- import(array) {
- if (array.length !== this.array.length) {
- throw 'Cannot import array of different size';
- }
- this.array = array;
- }
- }
- module.exports = BloomFilter;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement