I just discovered the delightful ES6 destructuring syntax for lists, i.e.
ls = [1, 2, 3]
[first, ...rest] = ls
which sets first to 1 and rest to [2,3]. However, is it possible to split the list into rest=[1,2] and last=3 using similar syntax?
I didn't have any luck googling it. I tried some obvious guesses for such a syntax (see below), but they all produced syntax errors.
[rest..., last] = ls
[...rest, last] = ls
I suppose I could do it by reversing the list twice, so an alternate solution to my question would be a constant time list reversal function.
What is commonly called "array destructuring" is actually destructuring an iterable, of which an array is a special case. The thing about iterables is that they can be infinite, or "lazy". That is the reason that you cannot destructure into some arbitrary number of elements followed by the last one:
const [...first, last] = integers();
because integers could be
function* integers() {
let n = 0;
while (true) yield n++;
}
and then what would last be?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With