用对象展开来写对象操作的纯函数

纯函数的一个原则是“不会产生副作用”。

一、数组操作 

定义

 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 }

 

posted @ 2019-01-10 23:56  longorYang  阅读(367)  评论(0编辑  收藏  举报