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.

Revisions

  1. Sigmus created this gist Aug 30, 2015.
    29 changes: 29 additions & 0 deletions xpto.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    ---
    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.

    ```javascript
    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];
    };
    }
    ```