Hacker News new | ask | show | jobs
by dandare 1606 days ago
You made two mistakes: You optimise prematurely and your assumption is incorrect.

Premature optimisation:

In most cases the performance would not matter. Instead of optimising for performance you should optimise for readability. IMHO IFs and FORs are way more readable in any context than any language specific methods like REDUCE and MAX.

Incorrect optimisation:

At least in modern browsers, simple IFs and FORs are the most optimised methods of doing anything. See for instance https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_... (Operations per second, higher is better).

4 comments

Conversely if I saw someone use a for loop (especially one with mutation) where a trivial usage higher order function existed, and I was giving a “leetcode” interview (which I refuse to do), I would take it as a signal that there is an important missing concept if it were not corrected when prompted.

The idea that “reduce” is language specific is frankly mind boggling. It’s no more language specific than a loop.

I am talking about my own time and resources, not those of a computer - say, it might take ~one hour to come up with a solution for problem x. It might very well be not the best solution either, just the one that works okay (we've all been there). Or I could look up what other people have done in 2 minutes - say I'm comparing solutions too, that would make it 10 minutes. That's 50 minutes of work I can spend elsewhere. Much more efficient.
I see. I completely agree.
Thank you for the nice exchange and learning opportunity though :)
As someone who prefers constructs like map, reduce, etc to loops this is a key example of why it’s important to a) ask why the candidate went that route and have a conversation about pros and cons and b) recognize that this is one of those no right answer opinion things and not hold it against them if they think different than you

Mind you I’m talking in general and now in browser specifically

Explicit loops are only more readable in languages that suck.
Well, the thread is about Javascript...

I take the exception that on this case in particular, the reduce is much more readable than a loop. Javascript isn't completely on the "anything non-imperative could as well be in machine code" league, but has plenty of problems that appear when you try to write other kinds of declarative code.