Hacker News new | ask | show | jobs
by kaesve 1421 days ago
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.

1 comments

Can you expand on your first trick? What is the problem being solved and what is a practical use case? I'm not sure I follow.