@ManavMisra/

Immutability Demo

Nodejs

Modified from 'Composing Software' by Eric Elliot

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const addToCart = (cart, item, quantity) => {
  return {
    
    // Developer's Note: Replace `concat` with SPREAD
    items: [...cart.items, ...[{
      item,
      quantity
    }]],
  };
};

const originalCart = {
  items: [
    {
      "item": {
        "name": "Digital SLR Camera Orginal",
        "price": "1494"
      },
      "quantity": 10
    }
  ]
};

const newCart = addToCart(
  originalCart,
  {
    name: "Digital SLR Camera",
    price: '1495'
  },
  1
);

console.log(
  JSON.stringify(originalCart, undefined, 2)
);

console.log('---');

console.log(
  JSON.stringify(newCart, undefined, 2)
);
node v10.16.0