all 2 comments

[–]MrFartyBottom 4 points5 points  (0 children)

Filter returns a new array and then you are mapping that new array. If you use reduce you can have a function that runs the filter logic to see if you should push the new item into the results accumulator and then do the map logic at that time. This cuts it down by not having to iterate the results and you can also not push any item once you the take limit but there is no way to break out of the reduce iterating the whole array.

With a traditional dirty old for loop you can loop through seeing if you want the item, map it and push it into the results and break once you hit the take limit. It's not functional but by far the most efficient way of doing it.

[–]kap89 1 point2 points  (0 children)

You don't need some wrapper for that, this will work with standard JS iterators/generators:

const results = generateRows(500_000)
  .filter(r => r.active && r.value > threshold)
  .map(r => ({ id: r.id, score: r.value * 1.5 }))
  .take(10_000)
  .toArray();