Skip to content
loading...

Peek-able loop

adam_cyclones profile image Adam Crockett github logo ・1 min read  

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;
    }
}

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

Nice relationship there.

twitter logo DISCUSS
Discussion
markdown guide
Classic DEV Post from Jul 27 '19

If You Don't Know, Now You Know - GitHub Is Restricting Access For Users From Iran And A Few Other Embargoed Countries

Please help our cause against modern-day discrimination

Adam Crockett profile image
I work at ForgeRock as a Front End Engineer, I play with all sorts really. Lately WASM is my toy of interest.