Hacker News new | ask | show | jobs
by azangru 673 days ago
The first example of a good refactor is a meh refactor at best, and possibly a bad refactor. Array methods such as map or filter are not "more conventional" in javascript; they are "as conventional" as for-loops, and arguably less "conventional", given how for-loops have been around since the introduction of the language. They are also inevitably more expensive than for-loops (every cycle creates an anonymous function; a map followed by a filter means another iteration of the array). The original example was fine; there was no need to "refactor" it.
2 comments

> every cycle creates an anonymous function

No, that's not how it works. The function is evaluated once before the call and passed as an argument, then internally reused.

Also, you're microptimizing. Prioritizing supposed performance over readability.

And yes, for-loops and mutable structures are more error prone than map-filter-reduce. The original is OK but could be better.

> No, that's not how it works. The function is evaluated once before the call and passed as an argument, then internally reused.

Yes, sorry; you are right of course.

Disagree on this. filter and map are much more readable and especially extensible than result-arrays. Plus it eliminates out-of-bonds indexing.

See the variable name. It's forced to be 'result' so that it's consistent with the result-array style. Therefore it lacks a descriptive name.

For the functional methods, you can easily assign the filter(age > 18) result to an intermediate variable like adultUsers to make the code even more descriptive. Useful when you have more steps. With the result-array approach, you'd have to repeat the looping code or bury the description deep in the loop itself and so you usually avoid that.

> much more readable

That’s down to preference.

Doesnt both filter and map copy the array increasing gc pressure?