DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

 

Infinitely loop over an array

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
Enter fullscreen mode Exit fullscreen mode

Thanks for reading πŸ’™

Follow @codedrops.tech for more.

Instagram ● Twitter ● Facebook

Micro-Learning ● Web Development ● Javascript ● MERN stack

codedrops.tech


Projects

File Ops - A VS Code extension to easily tag/alias files & quick switch between files

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.