Search code examples
javascriptjqueryiterationliquidcycle

Javascript / jQuery function similar to Liquid: cycle


Is there a function in JavaScript/jQuery similar to Liquid cycle as described below?

Loops through a group of strings and outputs them in the order that they were passed as parameters. Each time cycle is called, the next string that was passed as a parameter is output.

Input:

{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}

Output:

one
two
three
one

I have been trying to look at loop, forEach, do/while but can't get the idea.
Thanks for any suggestion.


Solution

  • You could use a closure,
    inside the outer scope you define a variable which keeps track of the index;
    while the returned function increments or resets the index, and returns the corresponding item.

    Here's an example:

    function cycle(arr) {
      cycle.i = -1
    
      //return a closure for cycling
      return function() {
        cycle.i = cycle.i < arr.length - 1 ? cycle.i + 1 : 0
    
        return arr[cycle.i]
      }
    }
    
    var it = cycle(['one', 'two', 'three'])
    setInterval(function() {
      console.log(it())
    }, 500)