1. 程式人生 > >用對象展開來寫對象操作的純函數

用對象展開來寫對象操作的純函數

undefine efi rem state define rdquo json ret string

純函數的一個原則是“不會產生副作用”。

一、數組操作

定義

 1 const state = {
 2   cart: [
 3     {
 4       product: ‘bread 700g‘,
 5       quantity: 2,
 6       unitCost: 1
 7     },
 8     {
 9       product: ‘milk 500ml‘,
10       quantity: 1,
11       unitCost: 2
12     },
13     {
14       product: ‘app 500g‘,
15 quantity: 1, 16 unitCost: 3 17 } 18 ]

 1 let push = () => {
 2   let item = {
 3     product: ‘cake 500g‘,
 4     quantity: 3,
 5     unitCost: 49
 6   }
 7   return {
 8     ...state,         //展開state
 9     cart: [           //解構得到 cart
10       ...state.cart,  //
展開cart 11 item //在末尾增加item 12 ] 13 } 14 }
1 let unshift = () => {
2   let item = {
3     product: ‘cake 500g‘,
4     quantity: 3,
5     unitCost: 49
6   }
7   return {...state,cart: [item, ...state.cart]}
8 } 

1 let removeAt = (index) => {
2   return
{ 3 ...state, 4 cart: [ 5 ...state.cart.slice(0, index), 6 ...state.cart.slice(index + 1) 7 ] 8 } 9 }

 1 let changeAt = (index, item) => {
 2   return {
 3     ...state,
 4     cart: [
 5       ...state.cart.slice(0, index),
 6       item,
 7       ...state.cart.slice(index + 1)
 8     ]
 9   }
10 }

二對象操作

定義

1 const state = {
2   product: ‘bread 700g‘,
3   quantity: 2,
4   unitCost: 1
5 }

1 let add = () => {
2   let price = ‘2.00‘
3   return {
4     ...state,         //展開state
5     price
6   }
7 }

1 let _delete = () => {
2   return JSON.parse(JSON.stringify({
3     ...state,
4     unitCost: undefined
5   }))
6 }

1 let change = () => {
2   return {
3     ...state,
4     unitCost: 2
5   }
6 }

用對象展開來寫對象操作的純函數