Class: JsonBloomfilter

Inherits:
Object
  • Object
show all
Defined in:
lib/json-bloomfilter.rb,
lib/json-bloomfilter/version.rb,
lib/json-bloomfilter/bitarray.rb

Defined Under Namespace

Classes: BitArray

Constant Summary collapse

DEFAULTS =
{ "size" => 100, "hashes" => 4, "seed" => Time.new.to_i, "bits" => nil }
VERSION =
"0.1.5"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ JsonBloomfilter

Returns a new instance of JsonBloomfilter.



22
23
24
25
26
27
# File 'lib/json-bloomfilter.rb', line 22

def initialize options = {}
  items = options.delete("items")
  @options = merge_defaults_with options
  @bits = BitArray.new(@options["size"], @options["bits"])
  add(items) if items
end

Class Method Details

.build(capacity_or_items, error_rate) ⇒ Object

Raises:

  • (ArgumentError)


8
9
10
11
12
# File 'lib/json-bloomfilter.rb', line 8

def self.build capacity_or_items, error_rate
  capacity, items = capacity_or_items.is_a?(Array) ? [capacity_or_items.length, capacity_or_items] : [capacity_or_items, nil]
  raise ArgumentError.new("Capacity needs to be a positive integer") if capacity <= 0
  JsonBloomfilter.new :size => size_for(capacity, error_rate), :hashes => hashes_for(capacity, error_rate), :items => items
end

.hashes_for(capacity, error_rate) ⇒ Object



18
19
20
# File 'lib/json-bloomfilter.rb', line 18

def self.hashes_for capacity, error_rate
  (Math.log(2) * size_for(capacity, error_rate) / capacity).round
end

.size_for(capacity, error_rate) ⇒ Object



14
15
16
# File 'lib/json-bloomfilter.rb', line 14

def self.size_for capacity, error_rate
  (capacity * Math.log(error_rate) / Math.log(1.0 / 2**Math.log(2))).ceil
end

Instance Method Details

#add(keys) ⇒ Object



29
30
31
32
33
34
# File 'lib/json-bloomfilter.rb', line 29

def add keys
  [keys].flatten.each do |key|
    indexes_for(key).each { |index| @bits.add(index) }
  end
  nil
end

#clearObject



45
46
47
# File 'lib/json-bloomfilter.rb', line 45

def clear
  @bits = BitArray.new(@options["size"])
end

#test(keys) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/json-bloomfilter.rb', line 36

def test keys
  [keys].flatten.each do |key|
    indexes_for(key).each do |index|
      return false if @bits.get(index) == 0
    end
  end
  true
end

#to_hashObject



49
50
51
# File 'lib/json-bloomfilter.rb', line 49

def to_hash
  @options.merge({ "bits" => @bits.field })
end

#to_jsonObject



53
54
55
# File 'lib/json-bloomfilter.rb', line 53

def to_json
  JSON.generate to_hash
end