Skip to content

Instantly share code, notes, and snippets.

@felipecesr
Forked from ahmed-musallam/Circular.js
Created November 30, 2021 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipecesr/fb9dc7f9b268791e4219f80b229cffc6 to your computer and use it in GitHub Desktop.
Save felipecesr/fb9dc7f9b268791e4219f80b229cffc6 to your computer and use it in GitHub Desktop.
A simple circular javascript data structure (backed by an array)
/**
* 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