Source: BloomFilter.mjs

  1. import xxhash from "xxhash-wasm";
  2. const { h32 } = await xxhash();
  3. /**
  4. * BloomFilter Class
  5. * Represents a BloomFilter Object
  6. */
  7. class BloomFilter {
  8. /**
  9. * BloomFilter Constructor
  10. * @param {number} [size=512] - Number of elements in the Bloom Filter, default 512
  11. * @param {number} [size=3] - Number of rounds of hashing, default 3
  12. */
  13. constructor(size = 512, hash = 3) {
  14. if (size <= 1) throw new Error("Size should be bigger than 1");
  15. if (hash < 1) throw new Error("Hash should be bigger than 1");
  16. this.size = size;
  17. this.hash = hash;
  18. // Create ArrayBuffer
  19. this.view = new DataView(new ArrayBuffer(this.size));
  20. }
  21. /**
  22. * Add a new element to the Bloom Filter
  23. * @param {string} input - Element to add - If array is provided all the elements will be added
  24. */
  25. add(input) {
  26. if (!Array.isArray(input)) input = [input];
  27. for (let value of input) {
  28. for (let i = 0; i < this.hash; i++) {
  29. value = h32(value);
  30. this.view.setInt8(parseInt(value, 16) % this.size, 1);
  31. }
  32. }
  33. }
  34. /**
  35. * Returns if element may be present in the Bloom Filter
  36. * @param {string} input - Element to check - If array is provided all the elements will be checked
  37. * @returns {boolean} - True - If element may be present, False if element is definitely not present, if array was provided an boolean array will be returned
  38. */
  39. has(input) {
  40. if (!Array.isArray(input)) {
  41. let value = input;
  42. for (let i = 0; i < this.hash; i++) {
  43. value = h32(value);
  44. if (!this.view.getInt8(parseInt(value, 16) % this.size)) return false;
  45. }
  46. return true;
  47. } else {
  48. const output = [];
  49. for (let value of input) output.push(this.has(value));
  50. return output;
  51. }
  52. }
  53. }
  54. export { BloomFilter };