How to make circular pairs
Circular pairs are when a collection's elements are paired with the next one, and the last one is paired with the first. For example, for elements 1, 2, 3
, it is [1, 2], [2, 3], [3, 1]
.
It is useful when you have some points and want to draw lines between them, closing the loop after the last one.
To make circular pairs from an array of points, use the map
function, present in every Array.
For a quick recap, map
's iteratee function gets (element, index, array)
, where element
is the current element, index
is the current element's index, and array
is the whole collection.
To make circular pairs, use:
array.map((e, i, a) => [e, a[(i + 1) % a.length]]);
This makes an array with the same length as the original one:
[ ]
=>[ ]
[1]
=>[[1, 1]]
[1, 2]
=>[[1, 2], [2, 1]]
Why does it work?
The next index is i + 1
. To prevent overflow, modulo with the number of elements: % a.length
. And finally, get the element from the resulting index: a[...]
.
For an empty array, the iteratee is never called, so a.length
will never be 0.