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
|
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.id]
if (index == null) {
return state
}
const data = [...state.data]
data[index] = action.item
return {
...state,
data,
byId: { ...state.byId, [action.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
}
}
/**
* @public
*/
export function add(item) {
return { type: ADD, item }
}
/**
* @public
*/
export function update(id, item) {
return { type: UPDATE, id, item }
}
/**
* @public
*/
export function remove(id) {
return { type: REMOVE, id }
}
/**
* @public
*/
export function receive(list) {
return { type: RECEIVE, list }
}
|