Sha256: 51559f62ddaa100096f34df1defec6fd443c2b5e725b2d9c96409ef193c4206d

Contents?: true

Size: 1.23 KB

Versions: 4

Compression:

Stored size: 1.23 KB

Contents

JsonBloomfilter = (options = {}) ->
  @options =
    size: 100,
    hashes: 4,
    seed: (new Date().getTime() / 1000),
    bits: null

  @options[key] = value for key, value of options
  @bits = new JsonBloomfilter.BitArray(@options["size"], @options["bits"])
  this

JsonBloomfilter.build = (capacity, error_rate) ->
  size = Math.ceil(capacity * Math.log(error_rate) / Math.log(1.0 / Math.pow(2,Math.log(2))))
  hashes = Math.round(Math.log(2) * size / capacity)
  new JsonBloomfilter({size: size, hashes: hashes})

JsonBloomfilter.prototype.add = (key) ->
  @bits.add(index) for index in @indexesFor(key)
  return

JsonBloomfilter.prototype.test = (key) ->
  for index in @indexesFor(key)
    return false if @bits.get(index) == 0
  true

JsonBloomfilter.prototype.clear = ->
  @bits = new JsonBloomfilter.BitArray(@options["size"])
  return

JsonBloomfilter.prototype.toHash = ->
  hash = {}
  hash[key] = value for key, value of @options
  hash["bits"] = @bits.field
  hash

JsonBloomfilter.prototype.toJson = ->
  JSON.stringify @toHash()

JsonBloomfilter.prototype.indexesFor = (key) ->
  indexes = []
  for index in [0..@options["hashes"]-1]
    indexes.push (JsonBloomfilter.Zlib.crc32("#{key}:#{index+@options["seed"]}") % @options["size"])
  indexes

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
json-bloomfilter-0.1.2 coffee/bloomfilter.coffee
json-bloomfilter-0.1.1 coffee/bloomfilter.coffee
json-bloomfilter-0.1.0 coffee/bloomfilter.coffee
json-bloomfilter-0.0.6 coffee/bloomfilter.coffee