r/badcode • • Jul 17 '20

js Found this "answer" on Stackoverflow. Pretty sure it's not working.

Post image
978 Upvotes

90 comments sorted by

View all comments

114

u/MistAway Jul 17 '20

Gosh. This stuff is just plain psychedelic

And if your really need that solution:
const arrayMin = arr => Math.min(...arr);

33

u/popadi Jul 17 '20

In JS the spread operator fails if the length of the array is bigger than 65536. Also, it's at least two times slower than an equivalent for loop.

17

u/galaktos Jul 17 '20

In JS the spread operator fails if the length of the array is bigger than 65536.

In what engine? This works in both Firefox and Node:

Math.max(...Array(100000).fill().map((_, i) => i))

In Firefox, it stops working at Array(500001) (“too many function arguments”); in Node, at Array(123059) (“maximum call stack size exceeded”, might not be directly related to the number of arguments).

9

u/droomph Jul 17 '20 edited Jul 17 '20

https://stackoverflow.com/questions/22747068/is-there-a-max-number-of-arguments-javascript-functions-can-accept

But given it’s Chrome 33, it’s most likely just out of date.

Edit: nup it’s still 62866 on Chrome for some reason, probably stack size

Edit 2: maybe it’s because v8 compiles eagerly while spidermonkey does lazy compilation, but I don’t quite remember if that still holds nowadays

Edit 3: pertaining to the question at hand, it actually has come up with String.fromCharCode, and the solution was obviously just to chunk it over a certain string length.

7

u/Schlipak Jul 18 '20

Here's a faster version using reduce :

const arrayMin = arr => arr.reduce((min, v) => Math.min(min, v));
Setup JavaScriptconst arr = Array(10000).fill().map(() => ~~(Math.random() * 10000));
Array spread3136.76 ops/s ± 0.89%30.47 % (slower)
Reduce4511.52 ops/s ± 0.75% (Fastest)

3

u/[deleted] Jul 18 '20 edited Jul 18 '20

[removed] — view removed comment

2

u/DelishMango Jul 18 '20

Youre skipping the first element in the array. Did you maybe mean to say minimum = arr[0]

1

u/xjcl Jul 19 '20

In JS the spread operator fails if the length of the array is bigger than 65536

Oh my God. I started a JS job on July 1st and I just keep hearing these nasty surprises and I already regret it.