-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathorderById.js
More file actions
123 lines (104 loc) · 2.71 KB
/
Copy pathorderById.js
File metadata and controls
123 lines (104 loc) · 2.71 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// @flow
import type { ID_TYPE } from './types';
type OrderByIdConfigurationType = {
fetched?: Array<string>,
replaced?: Array<string>,
added?: Array<string>,
removed?: Array<string>,
changed?: Array<string>,
elementChanged?: Array<string>,
idKey?: string,
orderKey?: string,
elementKey?: string,
newElementKey?: string,
};
type OrderByIdActionType = {
type: string,
payload: {
order?: Array<ID_TYPE>
},
};
const orderById = (configuration: OrderByIdConfigurationType) => (
state: {[ID_TYPE]: Array<ID_TYPE>} = {},
action: OrderByIdActionType,
): {[ID_TYPE]: Array<ID_TYPE>} => {
const {
fetched,
replaced,
added,
removed,
changed,
idKey = 'id',
orderKey = 'order',
elementKey = 'element',
newElementKey = 'newElement',
} = configuration;
const { payload } = action;
if (fetched != null && fetched.includes(action.type)) {
const order = payload[orderKey];
if (order && order.constructor === Array) {
const objectId = payload[idKey];
const originalOrder = state[objectId] || [];
const stateSet = new Set(originalOrder);
const difference = order.filter(
id => !stateSet.has(id)
);
return {
...state,
[objectId]: [
...originalOrder,
...difference,
],
};
}
}
if (added != null && added.includes(action.type)) {
const objectId = payload[idKey];
const toAdd = payload[elementKey];
if (state[objectId] && !state[objectId].includes(toAdd)) {
const originalOrder = state[objectId];
return {
...state,
[objectId]: [
...originalOrder,
toAdd,
],
};
}
}
if (removed != null && removed.includes(action.type)) {
const objectId = payload[idKey];
const toRemove = payload[elementKey];
if (state[objectId] && state[objectId].includes(toRemove)) {
const originalOrder = state[objectId];
return {
...state,
[objectId]: originalOrder.filter(i => i !== toRemove),
};
}
}
if (replaced != null && replaced.includes(action.type)) {
const order = payload[orderKey];
if (order && order.constructor === Array) {
const objectId = payload[idKey];
return {
...state,
[objectId]: order,
};
}
}
if (changed != null && changed.includes(action.type)) {
const objectId = payload[idKey];
const toChange = payload[elementKey];
const newValue = payload[newElementKey];
if (state[objectId]) {
const originalOrder = state[objectId];
return {
...state,
[objectId]: originalOrder.map(i => i === toChange ? newValue : i),
};
}
}
return state;
};
export default orderById;