Skip to content

Instantly share code, notes, and snippets.

@KINGSABRI
Last active December 25, 2015 06:49
Show Gist options
  • Select an option

  • Save KINGSABRI/6934762 to your computer and use it in GitHub Desktop.

Select an option

Save KINGSABRI/6934762 to your computer and use it in GitHub Desktop.
#https://github.com/bangthetable/CircularList/blob/master/lib/circular_list.rb
module CircularList
class List
def initialize(array)
@arr = array
end
def size
@arr.size
end
def fetch_previous(index=0)
index.nil? ? nil : @arr.unshift(@arr.pop)[index]
end
def fetch_next(index=0)
index.nil? ? nil : @arr.push(@arr.shift)[index]
end
def fetch_after(e)
fetch_next(@arr.index(e))
end
def fetch_before(e)
fetch_previous(@arr.index(e))
end
end
end
class CircularList < Array
def index
@index ||=0
@index.abs
end
def current
@index ||= 0
get_at(@index)
end
def next(num=1)
@index ||= 0
@index += num
get_at(@index)
end
def previous(num=1)
@index ||= 0
@index -= num
get_at(@index)
end
private
def get_at(index)
if index >= 0
at(index % self.size)
else
index = self.size + index
get_at(index)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment