Skip to content

Commit

Permalink
perf: ⚡️ faster add and lookup methods
Browse files Browse the repository at this point in the history
  • Loading branch information
lrodrigues-newstore committed Feb 25, 2025
1 parent 5688d73 commit f8785e4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 17 deletions.
20 changes: 12 additions & 8 deletions packages/bloom-filter/src/bloom-filter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { range } from '@pacote/array'
import { defaultHash } from './hash'
import type { Options } from './options'

Expand Down Expand Up @@ -26,19 +25,24 @@ export class BloomFilter<T extends { toString(): string }> {
}

add(element: T): void {
for (const i of range(0, this.hashes)) {
const hashedValue = this.hash(i, element.toString()) % this.size
const str = element.toString()
for (let i = 0; i < this.hashes; i++) {
const hashedValue = this.hash(i, str) % this.size
const position = Math.floor(hashedValue / 32)
this.filter[position] |= 1 << (hashedValue - position * 32)
this.filter[position] |= 1 << hashedValue % 32
}
}

has(element: T): boolean {
return range(0, this.hashes).every((i) => {
const hashedValue = this.hash(i, element.toString()) % this.size
const str = element.toString()
for (let i = 0; i < this.hashes; i++) {
const hashedValue = this.hash(i, str) % this.size
const position = Math.floor(hashedValue / 32)
return this.filter[position] & (1 << (hashedValue - position * 32))
})
if (!(this.filter[position] & (1 << hashedValue % 32))) {
return false
}
}
return true
}

toJSON(): SerialisedBloomFilter {
Expand Down
17 changes: 8 additions & 9 deletions packages/bloom-filter/src/counting-bloom-filter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { range } from '@pacote/array'
import { defaultHash } from './hash'
import type { Options } from './options'

Expand Down Expand Up @@ -26,14 +25,14 @@ export class CountingBloomFilter<T extends { toString(): string }> {
}

add(element: T): void {
for (const i of range(0, this.hashes)) {
for (let i = 0; i < this.hashes; i++) {
const position = this.hashPosition(i, element)
this.filter[position] += 1
}
}

remove(element: T): void {
for (const i of range(0, this.hashes)) {
for (let i = 0; i < this.hashes; i++) {
const position = this.hashPosition(i, element)
if (this.filter[position] > 0) {
this.filter[position] -= 1
Expand All @@ -42,12 +41,12 @@ export class CountingBloomFilter<T extends { toString(): string }> {
}

has(element: T): number {
return Math.min(
...range(0, this.hashes).map((i) => {
const position = this.hashPosition(i, element)
return this.filter[position]
}),
)
let min = Number.POSITIVE_INFINITY
for (let i = 0; i < this.hashes; i++) {
const position = this.hashPosition(i, element)
min = Math.min(min, this.filter[position])
}
return min
}

toJSON(): SerialisedCountingBloomFilter {
Expand Down

0 comments on commit f8785e4

Please sign in to comment.