Array tail destructuring

Awal Garg awalgarg at gmail.com
Sun Oct 2 08:50:26 UTC 2016


On Oct 2, 2016, at 9:30 AM, Olivier Lalonde <olalonde at gmail.com> wrote:

So what's the problem with `[...a, last]` that `[...a]` doesn't have? I
still don't get it.


> Since you don’t know when the iterator produced for `…a` will terminate,
there’s no way to know when you need to stop iterating `…a` and move onto
the next item `last`.


I think Olivier's point is that there is no way to know when you should
stop iterating in the case of `[...a]` either - hence the two cases are
equivalently problematic, if at all. Pulling the last element out *when*
the iteration stops is a different concern IMO which seems trivial to solve:


```
function destructureTail(it) {
    let head = [], tail;
    tail = it.next().value;
    for (let o of it) {
        head.push(tail);
        tail = o;
    }
    return { head, tail };
}

function* range(from, to) { while(from < to) yield from++; }

destructureTail(range(0, 0)); // empty iterator: head is an empty array and
tail is undefined
destructureTail(range(0, 1)); // only one element: head is an empty array
and tail is the single element
destructureTail(range(0, 2));
destructureTail(range(0, 3));
// destructureTail(range(0, Infinity)); // just hangs, like [...range(0,
Infinity)] would hang, which makes sense
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20161002/89212ff9/attachment.html>


More information about the es-discuss mailing list