Class: Metriks::UniformSample

Inherits:
Object
  • Object
show all
Defined in:
lib/metriks/uniform_sample.rb

Instance Method Summary collapse

Constructor Details

#initialize(reservoir_size) ⇒ UniformSample

Returns a new instance of UniformSample.



6
7
8
9
# File 'lib/metriks/uniform_sample.rb', line 6

def initialize(reservoir_size)
  @values = Array.new(reservoir_size, 0)
  @count  = Atomic.new(0)
end

Instance Method Details

#clearObject



11
12
13
14
15
16
# File 'lib/metriks/uniform_sample.rb', line 11

def clear
  @values.length.times do |idx|
    @values[idx] = 0
  end
  @count.value = 0
end

#sizeObject



18
19
20
21
# File 'lib/metriks/uniform_sample.rb', line 18

def size
  count = @count.value
  count > @values.length ? @values.length : count
end

#snapshotObject



23
24
25
# File 'lib/metriks/uniform_sample.rb', line 23

def snapshot
  Snapshot.new(@values.slice(0, size))
end

#update(value) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/metriks/uniform_sample.rb', line 27

def update(value)
  new_count = @count.update { |v| v + 1 }

  if new_count <= @values.length
    @values[new_count - 1] = value
  else
    idx = rand(new_count)
    if idx < @values.length
      @values[idx] = value
    end
  end
end