Class: Hikkmemo::RingBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/hikkmemo/ring_buffer.rb

Instance Method Summary collapse

Constructor Details

#initialize(capacity) ⇒ RingBuffer

Returns a new instance of RingBuffer.



3
4
5
6
# File 'lib/hikkmemo/ring_buffer.rb', line 3

def initialize(capacity)
  @buff = [nil] * capacity
  @i = 0
end

Instance Method Details

#last_n(n) ⇒ Object



19
20
21
22
23
# File 'lib/hikkmemo/ring_buffer.rb', line 19

def last_n(n)
  n = [n, @buff.size].min
  i = @i == 0 ? @buff.size : @i
  i < n ? @buff[-(n-i)..-1] + @buff[0..i-1] : @buff[i-n..i-1]
end

#popObject



14
15
16
17
# File 'lib/hikkmemo/ring_buffer.rb', line 14

def pop
  @i = (@i == 0 ? @buff.size : @i) - 1
  @buff[@i]
end

#push(elem) ⇒ Object



8
9
10
11
12
# File 'lib/hikkmemo/ring_buffer.rb', line 8

def push(elem)
  @buff[@i] = elem
  @i = @i == @buff.size - 1 ? 0 : @i + 1
  self
end