Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle function in Javascript

Tags:

javascript

I new to Javascript and I am looking for a cycle function. Here's Clojure's implementation I am trying to find a cycle function that infinitely loops/recurses through values of an array. I was hoping to find something like this in the underscore library, but I could not find anything suitable. Ideally I would like to use something like this:

 _.head(_.cycle([1,2,3]), 100)

This function would return an array of 100 elements:

[1,2,3,1,2,3,1,2,3,1,2,3,...]

Is there a function like this I can use in Javascript? Here's my feable attempt, but I can't seem to get it to work:

arr = [1,2,3,4,5,6,7,8,9];

var cycle = function(arr) {
  arr.forEach(function(d, i) {
    if (d === arr.length)
      return d
      d == 0
    else {return d}
  });
};

cycle(arr);

like image 979
turtle Avatar asked Feb 14 '23 22:02

turtle


1 Answers

You could do something like:

var cycle = function(array, count) {
    var output = [];

    for (var i = 0; i < count; i++) {
        output.push(array[i % array.length]);
    }

    return output;
}
like image 119
chinabuffet Avatar answered Feb 16 '23 13:02

chinabuffet