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

7

u/RoughDevelopment9235 Oct 06 '21

Now do it in JavaScript

18

u/Spood___Beest Oct 06 '21

[0,1,2,3,4].reduce((prev, n) => prev + (3*n))

4

u/RoughDevelopment9235 Oct 06 '21

Nice!

2

u/Spood___Beest Oct 06 '21

Now someone do it in Elixir :)

4

u/burnalicious111 Oct 06 '21

This is the way. Want a single value, use reduce.

2

u/Spood___Beest Oct 06 '21

That's what I usually jump to, but yesterday I had to write a javascript node for a version of an ETL that's so old I couldn't use "let", much less reduce. It was a bit of a shock haha

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)

8

u/JarvisPHD Oct 06 '21 edited Oct 06 '21
[...new Array(4).keys()].reduce((acc,n)=>acc+3*n,0) 

My attempt at a JS one liner

2

u/RoughDevelopment9235 Oct 06 '21

I’ll take it!

3

u/JarvisPHD Oct 06 '21

Thanks! Could be cleaner but JS has no equivalent of the range() function so I had to use a jank workaround

7

u/RoughDevelopment9235 Oct 06 '21

A feature of JavaScript is jank workarounds

2

u/Keve1227 Oct 06 '21 edited Oct 06 '21
new Array(5).fill().map((_, n) => n * 3).reduce((sum, v) => sum + v, 0);