Skip to content

Instantly share code, notes, and snippets.

@yuanchuan
Created March 24, 2012 04:51
Show Gist options
  • Save yuanchuan/2178390 to your computer and use it in GitHub Desktop.
Save yuanchuan/2178390 to your computer and use it in GitHub Desktop.
The ring data structure
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