Friday, October 13, 2017

Immutable data in JavaScript


Immutable Data

How not to change existing structure data itself but make a new copy of the data to work with

Object 

var a = {p1 : 'A', p2 : 3.142}
// {p1: "A", p2: 3.142}

// Make a copy of object referenced by a
// and replace the value of property p1 with the one specified (i.e. 'B')
var b = Object.assign({}, a, {p1 : 'B'})
// {p1: "B", p2: 3.142}

// same as above, but using the Object Spread Operator
var c = {...a, p1 : 'C'}
//{p1: "C", p2: 3.142}

Arrays

concat, filter, map, and reduce return new arrays.

var a = [1,2,3]
// [1, 2, 3]

// create a new array from contents of a and add another element to it (i.e. 4)
var b = a.concat(4)
// [1, 2, 3, 4]

Objects with Arrays

Objects that have arrays embedded in them.

var a = {p1 : "myList", ar : [1,2,3]}
// {p1: "myList", ar: Array(3)}
// ar : (3) [1, 2, 3]

var b = Object.assign({}, a)
// {p1: "myList", ar: Array(3)}
// ar : (3) [1, 2, 3]

// make a copy of array from object a into object b
// so that changes to either arrays do not effect eachother
b.ar = a.ar.concat(4)
// ar : (4) [1, 2, 3, 4]