immutable-js-oss / immutable-js

Immutable persistent data collections for Javascript which increase efficiency and simplicity.
https://immutable-js-oss.github.io/immutable-js/
MIT License
37 stars 6 forks source link

updateWhere to update a sublist #165

Open Methuselah96 opened 4 years ago

Methuselah96 commented 4 years ago

From @lpeliberty on Tue, 26 Nov 2019 08:20:07 GMT

What happened

Hello, I was trying to update a sublist of a List, but I've not found a proper way to do this (using only one method). Example : I have an Immutable cart with products and each products have a category and a price :

{
  cart: {
    products: [
      {
        category: 'category1',
        price: '10',
      },
      {
        category: 'category2',
        price: '20',
      },
    ]
  }
}

If I want to return the whole cart, and update only product where category is category1, I can do a map + update, a filter + merge like :

return cart.get('products').map(product => {
  if (product.category === 'category1') return product.set('price', 0);
  return product;
})

But with that, I only return products and not cart, so I have to merge... And sometimes I'm returning product without changes because it does not match my condition, it's not bad but not perfect right ?

return cart.updateWhere(
  'products',
  product => product.category === 'category1',
  product => product.set('price', 0),
})

Or with a updateInWhere for more complexe objects, It would be awesome for applications like react-redux (my use case).

Is it a bad idea ? Did I missed something in immutableJS docs that can do it ?

Thx to read.

Copied from original issue: https://github.com/immutable-js/immutable-js/issues/1752