update-in
Persistent functional object updates on vanilla js data structures (wraps react-addons-update)
Quick Examples
import {updateIn, merge, push, unshift, splice, assoc, dissoc} from 'update-in';
const val = {a: {b: 0, c: 2}, xs: [1, 2]};
updateIn(val, ['a', 'b'], v => v+1)
updateIn(val, ['a', 'b'], v => v+10)
let add = (...args) => args.reduce((a,b)=>a+b, 0);
updateIn(val, ['a', 'b'], add, 1, 2, 3)
updateIn(val, ['a', 'b'], v => 99)
merge({x: 1, y: 1}, {y: 2, z: 2})
updateIn(val, ['a'], merge, {c:99, d: 99})
updateIn(val, ['xs'], push, [3])
updateIn(val, ['xs'], push, [99])
updateIn(val, ['xs'], unshift, [0])
updateIn(val, ['xs'], splice, [[1, 1, 20]])
updateIn(val, ['xs'], splice, [[0, 1, 6, 5], [4, 0, 99, 99]])
updateIn(val, ['a'], assoc, 'b', 1);
updateIn(val, ['a'], assoc, 'b', 5, 'c', 6);
updateIn(val, ['a'], assoc, 'd', 4);
updateIn(val, ['a'], assoc, 'd', 4, 'e', 6);
updateIn(val, ['a'], assoc, 'd', 4, 'e')
updateIn(val, ['xs'], assoc, 0, 3);
updateIn(val, ['xs'], assoc, 0, 3, 1, 4);
updateIn(val, ['xs'], assoc, 2, 3);
updateIn(val, ['xs'], assoc, 1, false, 0)
updateIn(val, ['xs'], assoc, 1.5, 'not an int')
updateIn(val, ['xs'], assoc, -1, 'negative index?')
updateIn(val, ['xs'], assoc, 3, 'sparse arrays?')
const collections = {
object: {foo: 1, bar: 2, baz: 3},
array: [1, 2, 3, 4, 5, 6, 7]
};
updateIn(collections, ['object'], dissoc, 'bar')
updateIn(collections, ['object'], dissoc, 'foo', 'baz')
updateIn(collections, ['array'], dissoc, 1)
updateIn(collections, ['array'], dissoc, 2, 3, 4)
updateIn(collections, ['array'], dissoc, 1, 3, 5)
These combinators use structure sharing to preserve ===
for unchanged nodes, structure sharing is provided by react-addons-update. As of React 0.14, react-addons-update requires all of React as a peer dependency.
Bigger example
We can implement cursors in very few lines with updateIn
, see the examples subdirectory.