Skip to content

Commit 017cbc0

Browse files
committed
Add BloomFilter.withTargetError(n, error).
Fixes #1.
1 parent 4e089b9 commit 017cbc0

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

README.md

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ Usage
88
-----
99

1010
```javascript
11-
var bloom = new BloomFilter(
11+
const bloom = new BloomFilter(
1212
32 * 256, // number of bits to allocate.
1313
16 // number of hash functions.
1414
);
@@ -26,13 +26,17 @@ bloom.test("blah");
2626

2727
// Serialisation. Note that bloom.buckets may be a typed array,
2828
// so we convert to a normal array first.
29-
var array = [].slice.call(bloom.buckets),
30-
json = JSON.stringify(array);
29+
const array = [].slice.call(bloom.buckets);
30+
const json = JSON.stringify(array);
3131

3232
// Deserialisation. Note that the any array-like object is supported, but
3333
// this will be used directly, so you may wish to use a typed array for
3434
// performance.
35-
var bloom = new BloomFilter(array, 16);
35+
const bloom = new BloomFilter(array, 16);
36+
37+
// Automatically pick {m, k} based on number of elements and target false
38+
// positive error rate.
39+
const bloom = BloomFilter.withTargetError(1_000_000, 1e-6);
3640
```
3741

3842
Implementation

bloomfilter.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,12 @@
129129
return -this.m * Math.log(1 - bits / this.m) / this.k;
130130
};
131131

132+
BloomFilter.withTargetError = function(n, error) {
133+
const m = Math.ceil(-n * Math.log2(error) / Math.LN2);
134+
const k = Math.ceil(Math.LN2 * m / n);
135+
return new BloomFilter(m, k);
136+
};
137+
132138
// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
133139
function popcnt(v) {
134140
v -= (v >> 1) & 0x55555555;

0 commit comments

Comments
 (0)