Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Optimize for readability above everything else. Almost all of these examples I'd argue would be better suited for something like .map(). Little point in being overly cute, and if you are working with arrays large enough such that doing multiple passes is that much of a performance hit client-side, you have other issues going on.


> Almost all of these examples I'd argue would be better suited for something like .map()

Roughly half of his examples take an array and return either a differently-sized array, or a different data structure altogether. I can’t imagine how one could argue for a map in these cases.


Use the right tool for the job. Array to potentially different sized array? Use flatMap (which he implements in his example, albeit not it an optimal way). Array to single object or value? Use reduce.


Indeed, reduce is the swiss army knife since you can use it (sometimes when you shouldn't) to implement most of the other methods of map/filter etc.


I think the intent was simply to teach. Obviously if something can be done with map() instead of reduce(), it'll be more readable as map(). But seeing how the other list functions can be made out of reduce() helps you understand how it works.


That's also my minor nitpick, I feel like the syntax : `list.filter(myFilter).map(transform)` is clear about what I do and, each functions has a clear goal.

Otherwise I enjoyed reading this.


While your example reads a bit better, you’re now iterating through your list twice.


Most code isn't performance-critical.

This pattern will probably be dominated by the time taken to filter and map, not loop iteration.


Does JavaScript have adapters to covert lists into generators or lazy iterators?


Unfortunately not in a way that can optimize these methods. This is one reason the Java Streams API, which has a similar purpose (e.g. map, filter, flatMap, reduce, etc.), is a better design IMO because you can chain together method calls without creating (and iterating) the full array at each step.


Technically there is no iteration in filter/map/reduce at all.


That's incorrect. All of those functions are implemented using iteration.

Consider this excerpt from the .map() polyfill on MDN:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

    // 7. Let k be 0
    k = 0;

    // 8. Repeat, while k < len
    while (k < len) {
      // [loop body omitted]

      // d. Increase k by 1.
      k++;
    }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: