Array tail destructuring

Caitlin Potter caitpotter88 at gmail.com
Sun Oct 2 09:11:36 UTC 2016


On Oct 2, 2016, at 10:50 AM, Awal Garg <awalgarg at gmail.com> wrote:

>> 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`.

That statement is factually incorrect. There is a simple criteria to know when to terminate the iteration for a final rest element, which is when the iterator returns a result object with "done": true.

There is no condition to determine when to switch from a non-final rest element to some other element. That is a problem which needs to be addressed.

> 
> 
> 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/6b30a6b5/attachment.html>


More information about the es-discuss mailing list