This commit is contained in:
Jason Davies 2013-06-13 09:06:22 +01:00
commit 2529639ace
2 changed files with 22 additions and 0 deletions

View File

@ -72,6 +72,21 @@
return true;
};
// Estimated cardinality.
BloomFilter.prototype.size = function() {
var buckets = this.buckets,
bits = 0;
for (var i = 0, n = buckets.length; i < n; ++i) bits += popcnt(buckets[i]);
return -this.m * Math.log(1 - bits / this.m) / this.k;
};
// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
function popcnt(v) {
v -= (v >> 1) & 0x55555555;
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
// Fowler/Noll/Vo hashing.
function fnv_1a(v) {
var n = v.length,

View File

@ -48,6 +48,13 @@ suite.addBatch({
f.add(1);
assert.equal(f.test(1), true);
assert.equal(f.test(2), false);
},
"size": function() {
var f = new BloomFilter(1000, 4), i = -1;
while (++i < 100) f.add(i);
assert.inDelta(f.size(), 101.241308, 1e-6);
--i; while (++i < 1000) f.add(i);
assert.inDelta(f.size(), 1067.174487, 1e-6);
}
}
});