A simple function to mutate basic JavaScript variables in an immutable fashion
This package provides a getWithMutations(oldValue, newValue)
function that returns the oldValue
when the values are equal, or returns the newValue
when the values are different.
It operates recursively on objects or arrays, preserving nested value equality whenever possible.
Installation
Install the plugin with npm:
$ npm install --save with-mutations
Basic Usage
Mutating two equal values:
; const oldValue = a: 1 ;const newValue = a: 1 ;const result = ; console; // trueconsole; // false
Mutating two different values with some overlap:
; const oldValue = a: 1 b: 1 ;const newValue = a: 1 b: 2 ;const result = ; console; // falseconsole; // false console; // trueconsole; // false console; // falseconsole; // true
Custom mutatators
The getWithMutations
function takes an optional third argument which is the custom mutator.
The customMutator
should be a function which takes the oldValue and newValue as arguments and returns the result.
Note that the custom mutator is only executed if all of the following are true:
- Neither of the values are null or undefined
- The values are not identical references or primitive values
- The values are not both arrays or objects
; const oldValue = { };const newValue = { };oldValueprop = 'a';newValueprop = 'a'; const customMutator = oldValueprop === newValueprop ? oldValue : newValue; const result = console; // trueconsole; // false