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
|
import _ from 'lodash'
export const ADD = 'LIST_ADD'
export const UPDATE = 'LIST_UPDATE'
export const REMOVE = 'LIST_REMOVE'
export const RECEIVE = 'LIST_RECEIVE'
const defaultState = {
data: [],
byId: {},
indexOf: {},
}
export default function reduce(state = defaultState, action) {
switch (action.type) {
case ADD:
return {
...state,
data: [...state.data, action.item],
byId: { ...state.byId, [action.item.id]: action.item },
indexOf: { ...state.indexOf, [action.item.id]: state.data.length },
}
case UPDATE: {
const index = state.indexOf[action.item.id]
if (index == null) {
return state
}
const data = [...state.data]
data[index] = action.item
return {
...state,
data,
byId: { ...state.byId, [action.item.id]: action.item }
}
}
case REMOVE: {
const index = state.indexOf[action.id]
if (index == null) {
return state
}
const data = [...state.data]
const indexOf = { ...state.indexOf, [action.id]: null }
data.splice(index, 1)
for (let i = data.length - 1; i >= index; i--) {
indexOf[data[i].id] = i
}
return {
...state,
data,
indexOf,
byId: { ...state.byId, [action.id]: null },
}
}
case RECEIVE:
return {
...state,
data: action.list,
byId: _.fromPairs(action.list.map(item => [item.id, item])),
indexOf: _.fromPairs(action.list.map((item, index) => [item.id, index])),
}
default:
return state
}
}
export function add(item) {
return { type: ADD, item }
}
export function update(item) {
return { type: UPDATE, item }
}
export function remove(id) {
return { type: REMOVE, id }
}
export function receive(list) {
return { type: RECEIVE, list }
}
|