Skip to content

Instantly share code, notes, and snippets.

@ahmed-musallam
Created January 25, 2018 22:11
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ahmed-musallam/a8792eb488f8ef15e812c0680ea4a4a8 to your computer and use it in GitHub Desktop.
Save ahmed-musallam/a8792eb488f8ef15e812c0680ea4a4a8 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
@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