Skip to content

Comment on Lodash's Chain vs. Native Methodsparent

Comments

It's a slightly contrived example, but it demonstrates a real situation that can come up. Suppose instead it was:

  const drinkingAge = 21

  persons
    .map(p => ({ ...p, canDrink: p.age >= drinkingAge }))
    .filter(p => p.canDrink)
    .slice(0, 5);
Assuming we want `canDrink` to exist in those objects for later use, reversing the steps here would mean duplicating the logic and the work of computing it across the map() and the filter(), instead of keeping those concerns separate and re-using values:
  const drinkingAge = 21

  persons
    .filter(p => p.age >= drinkingAge)
    .map(p => ({ ...p, canDrink: p.age >= drinkingAge }))
    .slice(0, 5);
You could of course share the business logic by abstracting it into a function:
  const drinkingAge = 21

  function canDrink(person) {
    return person.age > drinkingAge
  }

  persons
    .filter(p => canDrink(p))
    .map(p => ({ ...p, canDrink: canDrink(p) }))
    .slice(0, 5);
But you'd still be doing the work twice. In this example it's trivial, but in a real-world scenario it might not be.

if you are using slice(0,5) then all the extra objects you mapped are lost and you have no reference to them.

Not true. slice() clones-and-drops the array, but not the objects inside.

but map also creates a new array, and within map you are not mutating the items of the old array but creating brand new ones no? [...].map(p => ({...p, canDrink}))

^ the original items of the array are not mutated in this map callback. you could mutate them if you really wanted, i.e.

[...].map(p => {p.canDrink = p.age > 20; return p})

but that is a straight up hack.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.