Javascript Iterator using generator function

PHOTO EMBED

Tue Oct 01 2024 17:02:19 GMT+0000 (Coordinated Universal Time)

Saved by @destinyChuck #json #vscode

function* createPeopleIterator() {
  let index = 0;
  while (true) {
    yield people[index++ % people.length];
  }
}

const iterator = createPeopleIterator();

console.log(iterator.next());
content_copyCOPY

This is a JavaScript generator function (denoted by the asterisk). It iterates of an array named 'people'. The person is defined by the people array and index. 'index++ % people.length' will loop through the array, once at the end, it will start again. Example: if index reaches 6, 6 % 5 is 1, next iteration, 7 % 5 is 2, ... and so on. Index++ will first use the current index and then increment.