Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class BloomFilter {
- constructor(size, hashCount) {
- this.size = size;
- this.hashCount = hashCount;
- this.bits = new Uint8Array(size);
- }
- add(value) {
- for (let i = 0; i < this.hashCount; i++) {
- const hash = this.hash(value, i);
- this.bits[hash] = 1;
- }
- }
- remove(value) {
- for (let i = 0; i < this.hashCount; i++) {
- const hash = this.hash(value, i);
- this.bits[hash] = 0;
- }
- }
- has(value) {
- for (let i = 0; i < this.hashCount; i++) {
- const hash = this.hash(value, i);
- if (this.bits[hash] !== 1) {
- return false;
- }
- }
- return true;
- }
- hash(value, seed) {
- let hash = 0;
- for (let i = 0; i < value.length; i++) {
- hash = (hash << 5) + hash + value.charCodeAt(i);
- hash = hash & hash; // Konvertierung in 32-Bit-Integer
- hash = Math.abs(hash);
- }
- return hash % this.size;
- }
- export() {
- return {
- size: this.size,
- hashCount: this.hashCount,
- bits: Array.from(this.bits),
- };
- }
- static import(data) {
- const bloomFilter = new BloomFilter(data.size, data.hashCount);
- bloomFilter.bits = Uint8Array.from(data.bits);
- return bloomFilter;
- }
- }
- // Beispiel für den Export und Import des Bloom-Filters:
- const bloomFilter = new BloomFilter(100, 3);
- bloomFilter.add('hello');
- const exportedData = bloomFilter.export();
- const importedBloomFilter = BloomFilter.import(exportedData);
- console.log(importedBloomFilter.has('hello')); // gibt "true" aus
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement