Array comprehensions with Spread operator

liorean liorean at gmail.com
Wed Apr 15 18:52:55 UTC 2015


On 15 April 2015 at 18:36, Jeremy Martin <jmar777 at gmail.com> wrote:
> Thanks, I gathered so after your response. This is why 99% of the time I
> wait for at least one other person to reply first, and why I should wait the
> remaining 1%... :)

Heck no!  You asking that question clarified the problem statement and
highlit that the example wasn't the perfect example code. Always good
to get assumptions checked and explanations of why alternative
solutions to specific use cases aren't what the issue is about.

For the record, what I can see, the code in the example is broken in
another way as well, the «i» in the reality example is not the
variable name used in the for-of.

Really, for these cases, I'd probably do something like a chained
reduce, somewhat like this:
«
js> let x=[0,1,2],y=[3,4,5],z=[6,7,8];
js> let flatten=(p,c)=>([...p,c]);
js> let add=(p,c)=>((+p)+(+c));
js> let concat=(p,c)=>(''+p+c);
js> let multireduce=(f,r)=>(a,...b)=>(a===void
0)?r:multireduce(f,a.reduce(f,r))(...b);
js> multireduce(flatten,[])(x,y,z);
[0, 1, 2, 3, 4, 5, 6, 7, 8]
js> multireduce(add,0)(x,y,z);
36
js> multireduce(concat,'')(x,y,z);
"012345678"
»

you could even edit that «multireduce» so that the no-initval variants
work, though I'm not bored enough to continue this exercise any
longer.
--
David "liorean" Andersson


More information about the es-discuss mailing list