Comment

Comment by kaesve

A 'trick' that I've grown fond of is for iterating over a circular list where the current and previous items form an edge, with a special case for the first edge, that is composed of the first and last items of the list (making it circular).

The 'normal' way to write a loop over this is something like:

for (let i = 0; i < ls.length; i++) {

    const j = i > 0 ? i - 1 : ls.length - 1;

    ...
}

A trick I got from sean barretts website (https://nothings.org/), is to use the for-loop initialization clause for the special case:

for (let i = 0, j = ls.length - 1; i < ls.length; j = i++) {

  ...
}

The work I do usually does not care about the performance improvement if there is any, but it feels good to avoid that per-iteration check.

parent kaesve 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton