-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreducer.js
108 lines (95 loc) · 1.97 KB
/
reducer.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* Imports
*/
import {
TODO_ADD,
TODO_REMOVE,
TODO_SET_TEXT,
TODO_SET_IMPORTANT,
TODO_SET_COMPLETED,
SET_ALL_COMPLETED,
CLEAR_COMPLETED,
URL_DID_UPDATE,
HYDRATE_STATE
} from './actions'
import ephemeral from 'redux-ephemeral'
/**
* Reducer
*/
function reducer (state, action) {
switch (action.type) {
case HYDRATE_STATE: {
return {
...state,
...action.payload
}
}
case TODO_ADD: {
const {text} = action.payload
return {
...state,
todos: [...state.todos, {text, important: false, completed: false}]
}
}
case TODO_REMOVE: {
return {
...state,
todos: state.todos.filter((todo, idx) => idx !== action.payload.idx)
}
}
case TODO_SET_TEXT: {
const {idx, text} = action.payload
return {
...state,
todos: updateArrayItem(state.todos, idx, todo => ({...todo, text}))
}
}
case TODO_SET_IMPORTANT: {
const {idx, important} = action.payload
return {
...state,
todos: updateArrayItem(state.todos, idx, todo => ({...todo, important}))
}
}
case TODO_SET_COMPLETED: {
const {idx, completed} = action.payload
return {
...state,
todos: updateArrayItem(state.todos, idx, todo => ({...todo, completed}))
}
}
case SET_ALL_COMPLETED: {
const {completed} = action.payload
return {
...state,
todos: state.todos.map(todo => ({...todo, completed}))
}
}
case CLEAR_COMPLETED: {
return {
...state,
todos: state.todos.filter(todo => !todo.completed)
}
}
case URL_DID_UPDATE: {
return {
...state,
url: action.payload.url
}
}
}
return ephemeral(state, action)
}
/**
* Utilities
*/
function updateArrayItem (arr, idx, fn) {
return arr.map((item, curIdx) =>
idx === curIdx
? fn(item)
: item)
}
/**
* Exports
*/
export default reducer