Last active
December 25, 2015 06:49
-
-
Save KINGSABRI/6934762 to your computer and use it in GitHub Desktop.
Ruby circular doubly-linked list
http://sausheong.blogspot.com/2012/04/ruby-circular-doubly-linked-list.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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