Skip to content

Instantly share code, notes, and snippets.

@Sigmus
Created August 30, 2015 07:04
Show Gist options
  • Save Sigmus/1dbf58b2e73a0a66417a to your computer and use it in GitHub Desktop.
Save Sigmus/1dbf58b2e73a0a66417a to your computer and use it in GitHub Desktop.

layout: post title: Next circular array item

A function that returns the next item in a given array. Starts over when the last item is reached.

var next = nextCircularItem(['x', 'y', 'z']);

next(); // x
next(); // y
next(); // z
next(); // x
        // etc

function nextCircularItem(arr) {
  var len = arr.length;
  var current = -1;
  return function() {
    var next = current + 1;
    current = next === len ? 0 : next;
    return arr[current];
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment