.keys() returns an iterator. Iterators don't have the map function, [...Iterator] unrolls an iterator into an array.
Array(4).map() doesn't do anything, because Array() doesn't initialise the values, and map has an inbuilt skip for "Empty items".
node
> Array(4)
[ <4 empty items> ]
I tend to use Array(N).fill().map(). Not sure if it's computationally any cheaper or more expensive.
Edit: memory efficiency wise,
let result=0;
for (let i of Array.keys(N)){
result += i;
}
Is best, due to only generating a value for i each loop rather than allocating an array. It's not very accessible in a functional programming style though, so I'm not really a fan. (And if you're using node/js, it's not likely memory efficiency is one of your concerns)
12
u/Eoussama Oct 06 '21
[...Array(4).keys()].map(e => 3 * e).reduce((acc, v) => acc + v, 0)