Advertisement
rgruber

BloomFilter Class

Dec 25th, 2022
960
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.05 KB | Source Code | 0 0
  1. class BloomFilter {
  2.   constructor(size, hashCount) {
  3.     this.size = size;
  4.     this.hashCount = hashCount;
  5.     this.bits = new Uint8Array(size);
  6.   }
  7.  
  8.   add(value) {
  9.     for (let i = 0; i < this.hashCount; i++) {
  10.       const hash = this.hash(value, i);
  11.       this.bits[hash] = 1;
  12.     }
  13.   }
  14.  
  15.   has(value) {
  16.     for (let i = 0; i < this.hashCount; i++) {
  17.       const hash = this.hash(value, i);
  18.       if (this.bits[hash] !== 1) {
  19.         return false;
  20.       }
  21.     }
  22.  
  23.     return true;
  24.   }
  25.  
  26.   hash(value, seed) {
  27.     let hash = 0;
  28.     for (let i = 0; i < value.length; i++) {
  29.       hash = (hash << 5) + hash + value.charCodeAt(i);
  30.       hash = hash & hash; // Konvertierung in 32-Bit-Integer
  31.       hash = Math.abs(hash);
  32.     }
  33.  
  34.     return hash % this.size;
  35.   }
  36. }
  37.  
  38. // Beispiel für die Verwendung des Bloom-Filters:
  39. const bloomFilter = new BloomFilter(100, 3);
  40. bloomFilter.add('hello');
  41. console.log(bloomFilter.has('hello')); // gibt "true" aus
  42. console.log(bloomFilter.has('world')); // gibt "false" aus (mit hoher Wahrscheinlichkeit)
  43.  
Tags: BloomFilter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement