Skip to content

Instantly share code, notes, and snippets.

@ahmed-musallam
Created January 25, 2018 22:11
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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
@KevinRobertAndrews
Copy link

Hey, this is great. Thanks!

@jackusay
Copy link

jackusay commented Jun 7, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment