Immutable.js Map set vs update
I would like to change a value at a key in a Map I have. Other than the fact that using update
will give me an error if the key I ask to update doesn't exist, what benefit is there (if any) to using update
over set
? I find set
to be significantly more concise/cleaner. In fact, based on the documentation one could (blindly) argue that set
is actually more efficient than update
since set
doesn't have to perform the get
for the updater
function.
Answer
update
is more powerful when your new value is the result of a transform of 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 transforms to your data in this way becomes more common when you start building your algorithms around your data (as in FP) instead of the other way around. I’ve done things before in a game like game.update('player', moveLeft)
.
If you know what the new value is, though, then just use set
as update(key, x => val)
is rather silly.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM