lib/bluepill/util/rotational_array.rb in bluepill-0.0.2 vs lib/bluepill/util/rotational_array.rb in bluepill-0.0.3

- old
+ new

@@ -1,17 +1,21 @@ module Bluepill module Util class RotationalArray < Array def initialize(size) - super - @index = 0 + super(size) + + @capacity = size + @counter = 0 end def push(value) - self[@index] = value - @index = (@index + 1) % self.size - puts @index + idx = rotational_idx(@counter) + self[idx] = value + + @counter += 1 + self end alias_method :<<, :push def pop @@ -25,10 +29,30 @@ def unshift raise "Cannot call unshift on a rotational array" end def last - self[@index - 1] + return if @counter.zero? + + self[rotational_idx(@counter - 1)] + end + + def first + return if @counter.zero? + return self[0] if @counter <= @capacity + + self[rotational_idx(@counter)] + end + + def clear + @counter = 0 + super + end + + private + + def rotational_idx(idx) + idx % @capacity end end end end