This article introduces the basic use of immutability-Helper plug-in, and introduces the usage and precautions of related API in detail.


concept

To understand the concept of Immutable data, Immutable data is data that, once created, cannot be changed. Every time an Immutable object is modified, a new Immutable object is returned to ensure that the data is Immutable. However, because the Immutable API and usage can be difficult to learn, you can use the immutability-Helper tool to manipulate native JS objects. This article mainly introduces the usage of immutability-Helper.

The source code

Source location

Welcome to Star! Welcome to Watch!

Summary of Matters needing attention

  • Immutability-helper does not modify the original object, but returns a new one

  • $push, $unshift, and $splice must be arrays or an error will be reported

  • The target of $add and $remove must be Set or Map

  • The rest of the apis can be used for arbitrary data

  • The argument to $splice is an array of operations that perform multiple operations on the target array at once, but the items in the parameter Arrays are executed sequentially, so pay attention to the order

  • Any API can be used within a multi-tier structure. See examples of extended usage

  • Multiple API operations can be performed simultaneously, but note that when multiple apis are executed in a single statement, only the last one is executed!! . See note usage examples

Commonly used API

  • {$push: array} pushes all the items in the array into the target array

  • {$unshift: array} unshift all items in the array to the target array

  • $splice: array of Arrays {$splice: array of Arrays}

    PS: The items in the parameter Arrays are applied sequentially, so the order is important. During the operation, the pointer to the target may change

  • {$set: any} replaces the target with an any value

  • {$toggle: array of strings} toggles the subscript or attribute value provided in the array argument to the opposite Boolean value

  • {$unset: array of strings} Removes the list of keys in the array parameter from the target object

  • {$merge: object} merges the key of the object parameter with the target

  • {$apply: function} passes the current value to the function and updates it with the new return value

  • {$add: array of objects} adds values to a Set or Map. When added to Set, array is the array of objects to be added; when added to Map, array is the array of [key, value]

  • {$remove: array of strings} Removes the list of keys in the parameter array from a Set or Map

API usage and examples

Initialize four variables on which all subsequent API operations are based

const initialObject = {
    name: 'Jack'.age: 22.gender: 'Man'
};
const initialArray = ['a'.'b'.'c'.'d'.'e'];
const initialSet = new Set(['2'.'0'.'1'.'9'.'pig'.'years'.'fast'.'music']);
const initialMap = new Map([['id'.'1'], ['color'.'blue'], ['alias'.'map']]);
Copy the code

{$push: array}

/** * API: {$push: array} * Adds all the elements contained in the array to the end of the initialArray as a new array
const pushArray = update(initialArray, { $push: ['f']});console.log('pushArray:', pushArray);  // => [ 'a', 'b', 'c', 'd', 'e', 'f' ]
Copy the code

{$unshift: array}

/** * API: {$unshift: array} * Adds all elements contained in the array ['f'] to the front of the initialArray as a new array */
const unshiftArray = update(initialArray, { $unshift: ['f']});console.log('unshiftArray:', unshiftArray);   // => [ 'f', 'a', 'b', 'c', 'd', 'e' ]
Copy the code

{$splice: array of arrays}

/** * API: {$splice: Array of Arrays contains all the operations that need to be performed. The first element of array represents the subscript and the second element represents the number of deletions. The third element represents the element that needs to be inserted into the initialArray. * 2. The two operations are not executed at the same time, but in sequence. The subsequent operations are executed on the result of the previous operation
const spliceArray = update(initialArray, { $splice: [[1.2], [2.0.'f'.'g']]});console.log('spliceArray:', spliceArray);  // => [ 'a', 'd', 'f', 'g', 'e' ]
Copy the code

{$set: any}

/** * API: {$set: any} * Can replace the value of an index or attribute in an array or object */
// Change the subscript 1 element in the initialArray array to 'f'
const setArray = update(initialArray, { 1: { $set: 'f'}});console.log('setArray', setArray);  // => [ 'a', 'f', 'c', 'd', 'e' ]

// Change the age attribute in initialObject to 26
const setObject = update(initialObject, { age: { $set: 26}});console.log('setObject', setObject);    // => { name: 'Jack', age: 26, gender: 'Man' }
Copy the code

{$toggle: array of strings}

/** * API: {$toggle: array of strings} * Toggle the values of subscripts or attributes in an array or object: any Truthy is switched to false, and any Falsy is switched to true */
// Toggle elements with subscripts 1 and 2 in initialArray
const toggleArray = update(initialArray, { $toggle: [ 1.2]});console.log('toggleArray:', toggleArray);    // => [ 'a', false, false, 'd', 'e' ]

const toggleObject = update(initialObject, { $toggle: [ 'name'.'gender']});console.log('toggleObject:', toggleObject);  // => { name: false, age: 22, gender: false }
Copy the code

{$unset: array of strings}

/** * API: {$unset: array of strings} * removes subscripts or attribute lists from arrays or objects */
InitialArray removes two elements with subscripts 1 and 2, but keeps placeholders
const unsetArray = update(initialArray, { $unset: [1.2]});console.log('unsetArray:', unsetArray.length, unsetArray); // 5 [ 'a', <2 empty items>, 'd', 'e' ]

// Delete the name and gender attributes of the initialObject
const unsetObject = update(initialObject, { $unset: ['name'.'gender']});console.log('unsetObject', unsetObject);    // unsetObject { age: 22 }
Copy the code

{$merge: object}

/** * API: {$merge: object} * Merges elements with the same subscript or attribute in the object from the target array or object. If the subscript or attribute is the same, the element in the object replaces the element in the target
// Replace 'a', 'b', 'c' in the initialArray array with 1, 2, 3
const mergeArray = update(initialArray, { $merge: [1.2.3]});console.log('mergeArray:', mergeArray);    // => [ 1, 2, 3, 'd', 'e' ]

// Merge initialObject and {name: 'Rose', gender: 'Woman', Hobby: 'Swimming'}} objects
const mergeObject = update(initialObject, { $merge: { name: 'Rose'.gender: 'Woman'.hobby: 'Swimming'}});console.log('mergeObject', mergeObject);    // => { name: 'Rose', age: 22, gender: 'Woman', hobby: 'Swimming' }
Copy the code

{$apply: function}

/** * API: {$apply: function} * applies function */ to a subscript or attribute in the target array or object
const apply = (val) = > val + '--apply'
// Apply to the elements with subscript 1 in the initialArray array
const applyArray = update(initialArray, { 1: { $apply: apply } });
console.log('applyArray:', applyArray);    // => [ 'a', 'b--apply', 'c', 'd', 'e' ]

// Apply for the name attribute in the initialObject
const applyObject = update(initialObject, { name: { $apply: apply } });
console.log('applyObject:', applyObject);  // => { name: 'Jack--apply', age: 22, gender: 'Man' }
Copy the code

{$add: array of objects}

/** * API: {$add: array of objects} */ $add: array of objects */
// Add elements from ['Hello', 'World'] to initialSet and return a new Set
const addSet = update(initialSet, { $add: ['Hello'.'World']});console.log('addSet:', addSet);    / / = > Set {' 2 ', '0', '1', '9', 'pig', 'in', 'fast' and 'happiness', 'Hello,' World '}

// Add elements in [[3, 'Hello'], ['width', '20px']] to initialMap and return a new Map
const addMap = update(initialMap, { $add: [[3.'Hello'], ['width'.'20px']]});console.log('addMap', addMap);  // => Map { 'id' => '1', 'color' => 'blue', 3 => 'Hello', 'width' => '20px' }
Copy the code

{$remove: array of strings}

/** * API: {$remove: array of strings} */
// Delete the 'pig' and 'year' elements in initialSet
const removeSet = update(initialSet, { $remove: ['pig'.'years']});console.log('removeSet:', removeSet);  / / = > removeSet: Set {' 2 ', '0', '1', '9', 'fast', 'music'}

// Delete the two key-value pairs corresponding to 'color' and 'alias' in initialMap
const removeMap = update(initialMap, { $remove: ['color'.'alias']});console.log('removeMap:', removeMap);  // => Map { 'id' => '1' }
Copy the code

Extend the usage

  • It can be used in multi-layer structure
/** * extended usage: */ can be used within a multi-layer structure
const initialConfig = {
    width: 100.height: 100.options: [{color: 'red'.shape: 'Square' },
        { color: 'blue'.shape: 'Circular'}}]// Use in multilayer structure
const multiConfig1 = update(initialConfig, { options: { color: { $set: 'pink'}}});console.log('multiConfig1:', multiConfig1);
/* => { width: 100, height: 100, options: [ { color: 'red', shape: 'Square' }, { color: 'blue', shape: 'Circular' }, color: 'pink' ] } */
Copy the code

Pay attention to the usage

  • Do not use multiple operations at the same time; otherwise, only the last operation will be performed
/** * Note usage: Do not use multiple operations at the same time, otherwise only the last operation will be performed */

const initialConfig = {
    width: 100.height: 100.options: [{color: 'red'.shape: 'Square' },
        { color: 'blue'.shape: 'Circular'}}]// Example: Only the last operation to set the color property will be performed
const multiConfig2 = update(initialConfig, { options: { $push: [{color: 'deepPink'.shape: 'Triangle'}},options: { color: { $set: 'pink'}}});console.log('multiConfig2:', multiConfig2);    
/* => { width: 100, height: 100, options: [ { color: 'red', shape: 'Square' }, { color: 'blue', shape: 'Circular' }, color: 'pink' ] } */
Copy the code