Created
April 14, 2017 18:20
-
-
Save ianwcarlson/df32dfa8eefd473181b4730dbd5bc5d1 to your computer and use it in GitHub Desktop.
Reference Comparison Immutable vs. Native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Map, List } = require('immutable'); | |
const mapBeforeI = Map({ a: 1, b: List([1, 2]) }); | |
// First let's experiment with an Immutable structure | |
// Perform set operation, but make the values the same | |
const mapAfterI = mapBeforeI.set('a', 1); | |
console.log(mapBeforeI === mapAfterI); // true | |
// Perform set operation, but make the values different | |
const mapAfterI2 = mapBeforeI.set('a', 2); | |
console.log(mapBeforeI === mapAfterI2); // false | |
// Perform deep set operation, but make the nested values the same | |
const mapAfterI3 = mapBeforeI.setIn(['b', 0], 1); | |
console.log(mapBeforeI === mapAfterI3); // true | |
// Perform deep set operation, but make the nested values different | |
const mapAfterI4 = mapBeforeI.setIn(['b', 0], 2); | |
console.log(mapBeforeI === mapAfterI4); // false | |
// Ok, works as expected! | |
// Now let's experiment with a native javascript structure | |
let mapBeforeN = { a: 1, b: [1, 2] }; | |
const mapBeforeN2 = mapBeforeN; | |
// Reference is shared | |
console.log(mapBeforeN === mapBeforeN2); // true | |
// Don't change anything, but create a new reference by copying | |
const mapAfterN = Object.assign({}, mapBeforeN); | |
// Even though the values remain the same, the triple equals | |
// compares the references which are different | |
console.log(mapBeforeN === mapAfterN); // false | |
// Now, the values still remain the same, but references are | |
// again changed | |
const mapAfterN2 = Object.assign({}, mapBeforeN, { a: 1 }); | |
console.log(mapBeforeN === mapAfterN2); // false | |
// Now, create a new reference, but assign the same values | |
mapBeforeN = { a: 1, b: [1, 2] }; | |
// Reference is changed | |
console.log(mapBeforeN === mapBeforeN2); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment