Advertisement
rgruber

BloomFilter Class w/ export, import

Dec 25th, 2022
1,171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.53 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.   remove(value) {
  16.     for (let i = 0; i < this.hashCount; i++) {
  17.       const hash = this.hash(value, i);
  18.       this.bits[hash] = 0;
  19.     }
  20.   }
  21.  
  22.   has(value) {
  23.     for (let i = 0; i < this.hashCount; i++) {
  24.       const hash = this.hash(value, i);
  25.       if (this.bits[hash] !== 1) {
  26.         return false;
  27.       }
  28.     }
  29.  
  30.     return true;
  31.   }
  32.  
  33.   hash(value, seed) {
  34.     let hash = 0;
  35.     for (let i = 0; i < value.length; i++) {
  36.       hash = (hash << 5) + hash + value.charCodeAt(i);
  37.       hash = hash & hash; // Konvertierung in 32-Bit-Integer
  38.       hash = Math.abs(hash);
  39.     }
  40.  
  41.     return hash % this.size;
  42.   }
  43.  
  44.   export() {
  45.     return {
  46.       size: this.size,
  47.       hashCount: this.hashCount,
  48.       bits: Array.from(this.bits),
  49.     };
  50.   }
  51.  
  52.   static import(data) {
  53.     const bloomFilter = new BloomFilter(data.size, data.hashCount);
  54.     bloomFilter.bits = Uint8Array.from(data.bits);
  55.     return bloomFilter;
  56.   }
  57. }
  58.  
  59. // Beispiel für den Export und Import des Bloom-Filters:
  60. const bloomFilter = new BloomFilter(100, 3);
  61. bloomFilter.add('hello');
  62. const exportedData = bloomFilter.export();
  63. const importedBloomFilter = BloomFilter.import(exportedData);
  64. console.log(importedBloomFilter.has('hello')); // gibt "true" aus
  65.  
Tags: BloomFilter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement