source code

mutate a copy of data without changing the original source 一个通过语法糖来避免deep copy带来的性能问题的不改变原数据的库

为了解决deep copies are expensive, and sometimes impossible, 设计出只改变需要改变的对象属性,复用未改变的,这就是这个库的核心思想

update() provides simple syntactic sugar around this pattern to make writing this code easier

  1. import update from 'immutability-helper';
  2. const newData = update(myData, {
  3. x: {y: {z: {$set: 7}}},
  4. a: {b: {$push: [9]}}
  5. });

Commands

  • {$push: array} push() all the items in array on the target.
  • {$unshift: array} unshift() all the items in array on the target.
  • {$splice: array of arrays} for each item in arrays call splice() on the target with the parameters provided by the item. Note: The items in the array are applied sequentially, so the order matters. The indices of the target may change during the operation.
  • {$set: any} replace the target entirely.
  • {$toggle: array of strings} toggles a list of boolean fields from the target object.
  • {$unset: array of strings} remove the list of keys in array from the target object.
  • {$merge: object} merge the keys of object with the target.
  • {$apply: function} passes in the current value to the function and updates it with the new returned value.
    • Shorthand syntax

update({a: 1}, {a: function}). That example would be equivalent to update({a: 1}, {a: {$apply: function}}).

  • {$add: array of objects} add a value to a Map or Set. When adding to a Set you pass in an array of objects to add, when adding to a Map, you pass in [key, value] arrays like so: update(myMap, {$add: [['foo', 'bar'], ['baz', 'boo']]})
  • {$remove: array of strings} remove the list of keys in array from a Map or Set.

extend

choose to use the extend functionality to add an $auto and $autoArray command:

import update, { extend } from 'immutability-helper';

extend('$auto', function(value, object) {
  return object ?
    update(object, value):
    update({}, value);
});

var state2 = update(state, {
  foo: {$autoArray: {
    0: {$auto: {
      bar: {$autoArray: {$push: ['x', 'y', 'z']}}
    }}
  }}
});