Created
March 24, 2012 04:51
-
-
Save yuanchuan/2178390 to your computer and use it in GitHub Desktop.
The ring data structure
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
var Ring = (function() { | |
function Ring(list) { | |
this._list = [].slice.call(list, 0); | |
this._length = this._list.length; | |
this._curr = -1; | |
}; | |
Ring.prototype = { | |
rollTo: function(idx) { | |
this._curr = idx % this._length; | |
if (this._curr < 0) this._curr += this._length; | |
return this._list[this._curr]; | |
}, | |
next: function() { | |
return this.rollTo(this._curr + 1); | |
}, | |
prev: function() { | |
return this.rollTo(this._curr - 1); | |
} | |
}; | |
return function(list) { | |
return new Ring(list); | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment