Mutate a piece of data in place leveraging a convenient set of commands.
Based on immutability-helper
.
import update from 'mutability-helper';
const state1 = ['x'];
update(state1, {$push: ['y']});
// state1 === ['x', 'y']
Originally, the immutability-helper
's selling point was the fact that it
didn't mutated the piece of data at all, returning a mutated copy of it to be
used instead.
But, sometimes you may want to update a piece of data in place, leveraging
those nice and convenient commands from that come from immutability-helper
(and they were originally inspired by MongoDB's query language).
That is why this project exists and it uses the same commands API from the
original immutability-helper
.
update()
provides simple syntactic sugar around this pattern to make writing this code easier. This code becomes:
import update from 'immutability-helper';
update(myData, {
x: {y: {z: {$set: 7}}},
a: {b: {$push: [9]}}
});
// myData is changed here
An nice introduction to commands API is available in original immutability-helpers
repo,
which also covers how to create additional commands.
Please not that the commands for the mutability-helper
are a bit different from the immutability-helpers
.
They have to be mutable and change the originalObject
correctly. Also, we start to pass originalSpec
as an argument,
it is needed sometimes for some special commands. $set
and $apply
have new requirements now.