r/ProgrammerHumor • • Oct 06 '21

Don't be scared.. Math and Computing are friends..

Post image
65.8k Upvotes

2.4k comments sorted by

View all comments

Show parent comments

12

u/Eoussama Oct 06 '21

[...Array(4).keys()].map(e => 3 * e).reduce((acc, v) => acc + v, 0)

3

u/MartiParti69 Oct 06 '21

Can't you skip the map and do the multiplication in the reduce to save one loop?

1

u/Nilstrieb Oct 06 '21

Why do you clone the keys?

4

u/Jetbooster Oct 06 '21 edited Oct 06 '21

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

1

u/Nilstrieb Oct 06 '21

Oh right, I confused it with Object.keys

1

u/lachlanhunt Oct 07 '21

You made an off by 1 error. Should use Array(5)