Created
January 25, 2018 22:11
-
-
Save ahmed-musallam/a8792eb488f8ef15e812c0680ea4a4a8 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
You can use the modular (%) operator: https://stackoverflow.com/questions/18725428/going-back-to-the-first-index-after-reaching-the-last-one-in-an-array