-
-
Save felipecesr/fb9dc7f9b268791e4219f80b229cffc6 to your computer and use it in GitHub Desktop.
A simple circular javascript data structure (backed by an array)
This file contains 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
/** | |
* A simple circular data structure | |
*/ | |
function Circular(arr, startIntex){ | |
this.arr = arr; | |
this.currentIndex = startIntex || 0; | |
} | |
Circular.prototype.next = function(){ | |
var i = this.currentIndex, arr = this.arr; | |
this.currentIndex = i < arr.length-1 ? i+1 : 0; | |
return this.current(); | |
} | |
Circular.prototype.prev = function(){ | |
var i = this.currentIndex, arr = this.arr; | |
this.currentIndex = i > 0 ? i-1 : arr.length-1; | |
return this.current(); | |
} | |
Circular.prototype.current = function(){ | |
return this.arr[this.currentIndex]; | |
} | |
/** | |
* USAGE | |
*/ | |
var c = new Circular([1,2,3,4]); | |
c.current(); // 1 | |
c.next(); // 2 | |
c.current(); // 2 | |
c.next(); // 3 | |
c.next(); // 4 | |
c.next(); // 1 | |
c.next(); // 2 | |
c.prev(); // 1 | |
c.current(); // 1 | |
c.prev(); // 4 | |
c.current(); // 4 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment