DEV Community

Adam Crockett 🌀
Adam Crockett 🌀

Posted on • Edited on

Peek-able loop

Rust has this concept of peek-able iterators, It means the ability to loop through a list and look ahead to the next item in the same iteration. Here is a generator function that makes this work, yes it's true that this can be done anyway but it's nicer this way.

If you want this in js just remove the signature type.

function* peekable(...iterable: Array<any>) {
  let i = 0;
  while (iterable.length) {
    yield [iterable[i], iterable[i + 1] || null];
    iterable.shift();
  }
}

// usage
for (const [currPerson, nextPerson] of peekable(👩‍🎤, 🧑‍🎤, 👨‍🎤)) {
    // ignore the end item with no 'next'
    if (nextPerson) {
        currPerson.next = nextPerson;
        nextPerson.prev = currPerson;
    }
}
Enter fullscreen mode Exit fullscreen mode

Last note before I go, shift is destructive so you could always just increment a variable instead.

Nice relationship there.

Top comments (0)