Skip to main content

Command Palette

Search for a command to run...

Infinitely loop over an array

Published
1 min readView as Markdown
const loopOverArray = (arr) => {
  let index = -1;

  const getNextElementFromArray = () => {
    index++;
    const nextIndex = index % arr.length;
    return arr[nextIndex];
  };

  return getNextElementFromArray;
};

const getNextElement = loopOverArray([1, 2, 3]);

console.log(getNextElement()); // 1
console.log(getNextElement()); // 2
console.log(getNextElement()); // 3
console.log(getNextElement()); // 1
D

Good example. However with JavaScript these days the generator function does exactly this with less overhead. 😉

1

More from this blog

Codedrops.tech

49 posts