6 ms·
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 edg
by kaesve 4y 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/ 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.
- phaistra 4y agoCan 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.