What is the shortest way to modify immutable objects using spread and destructuring operators

前端 未结 6 1140
无人及你
无人及你 2021-01-30 22:34

I\'m looking for a pure function, to modify my immutable state object. The original state given as parameter must stay untouched. This is especially useful when working with fra

6条回答
  •  半阙折子戏
    2021-01-30 23:22

    Actions on state, where state is considered immutable.

    Adding or Updating the value of a property:

    // ES6:
    function updateState(state, item) {
        return Object.assign({}, state, {[item.id]: item});
    }
    
    // With Object Spread:
    function updateState(state, item) {
      return {
         ...state,
         [item.id]: item
      };
    }
    

    Deleting a property

    // ES6:
    function deleteProperty(state, id) {
        var newState = Object.assign({}, state);
        delete newState[id];
        return newState; 
    }
    
    // With Object Spread:
    function deleteProperty(state, id) {
        let  {[id]: deleted, ...newState} = state;
        return newState;
    }
    
    // Or even shorter as helper function:
    function deleteProperty({[id]: deleted, ...newState}, id) {
        return newState;
    }
    
    // Or inline:
    function deleteProperty(state, id) {
        return (({[id]: deleted, ...newState}) => newState)(state);
    }
    

提交回复
热议问题