Immutable.js Map set vs update

I would like to change the value using the key on the Map that I have. Besides the fact that using update will give me an error if the key that I request for updating does not exist, what is the use of it (if any) when using update over set ? I find set significantly shorter / cleaner. In fact, based on the documentation, one could (blindly) state that set actually more efficient than update , since set should not execute get for the updater function.

+6
source share
2 answers

update more powerful when your new value is the result of converting the current value:

 const inc = (x) => (x + 1) const m = Immutable.Map({a: 1, b: 2, c: 3}) m.update('b', inc) #=> {a: 1, b: 3, c: 3}) 

vs. with set :

 m.set('b', inc(m.get('b')) 

This example is pretty trivial, but the pattern of applying transformations to your data this way becomes more common when you start building your algorithms around your data (like in FP ), and not vice versa. Ive done things before in a game like game.update('player', moveLeft) .

If you know what the new value is, then just use set , since update(key, x => val) pretty stupid.

+15
source

@MatthewHerbst said:

(...) wondered if it was still good practice to use the update or if the set was perfect

in his comment on @ andrew-marshall's answer

I do not think that this is about good or bad practice.

From what I understand, there are two different use cases:

  • the value you set is independent of the previous value: use set
  • the value you set depends on the previous value: use update

So, I donโ€™t think you should always use set over update (or vice versa), I think you should use this or that option depending on your use case

0
source

All Articles