Class: RingBuffer

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size = 8) ⇒ RingBuffer

Returns a new instance of RingBuffer.



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

def initialize(size = 8)
  @store = StaticArray.new(size)
  @start_idx = 0
  @length = 0
  @capacity = size
end

Instance Attribute Details

#lengthObject

Returns the value of attribute length.



5
6
7
# File 'lib/simms_structures/ring_buffer.rb', line 5

def length
  @length
end

Instance Method Details

#[](index) ⇒ Object

O(1)



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

def [](index)
  check_index(index)
  @store[relative_index(index)]
end

#[]=(index, value) ⇒ Object

O(1)



25
26
27
28
# File 'lib/simms_structures/ring_buffer.rb', line 25

def []=(index, value)
  check_index(index)
  @store[relative_index(index)] = value
end

#popObject

O(1)



31
32
33
34
35
# File 'lib/simms_structures/ring_buffer.rb', line 31

def pop
  check_index(0)
  @length -= 1
  @store[(@start_idx + @length) % @capacity]
end

#push(value) ⇒ Object

O(1) ammortized



38
39
40
41
42
43
44
# File 'lib/simms_structures/ring_buffer.rb', line 38

def push(value)
  resize! if @length == @capacity
  @store[(@start_idx + @length) % @capacity] = value
  @length += 1
  nil
  # debugger
end

#relative_index(index) ⇒ Object



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

def relative_index(index)
  (@start_idx + index) % @capacity
end

#shiftObject

O(1)



47
48
49
50
51
52
53
# File 'lib/simms_structures/ring_buffer.rb', line 47

def shift
  check_index(0)
  value = self[0]
  @start_idx = (@start_idx + 1) % @capacity
  @length -= 1
  value
end

#unshift(value) ⇒ Object

O(1) ammortized



56
57
58
59
60
61
# File 'lib/simms_structures/ring_buffer.rb', line 56

def unshift(value)
  resize! if @length == @capacity
  @start_idx = (@start_idx - 1) % @capacity
  @store[@start_idx] = value
  @length += 1
end