Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions lib/splitclient-rb/cache/filter/bloom_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,35 @@ module Filter
class BloomFilter
def initialize(capacity, false_positive_probability = 0.001)
@capacity = capacity.round
m = best_m(capacity, false_positive_probability)
@ba = BitArray.new(m.round)
@m = best_m(capacity, false_positive_probability)
reset_filter
@k = best_k(capacity)
end

def add(string)
return false if contains?(string)

positions = hashes(string)

positions.each { |position| @ba[position] = 1 }

true
end

def contains?(string)
!hashes(string).any? { |ea| @ba[ea] == 0 }
end

def clear
@ba.size.times { |i| @ba[i] = 0 }
@ba = nil
reset_filter
end

private

def reset_filter
@ba = BitArray.new(@m.round)
end

# m is the required number of bits in the array
def best_m(capacity, false_positive_probability)
-(capacity * Math.log(false_positive_probability)) / (Math.log(2) ** 2)
Expand Down
Loading