-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (37 loc) · 1.17 KB
/
index.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
import { matchPattern } from '../utils'
import * as F from '../fp-utils'
const INITIAL_STATE = {}
const makeEntitiesReducer = (
{ update, mergeById, updateById, removeById, reset },
) => (state = INITIAL_STATE, action) => {
if (matchPattern(update, action)) {
if(F.isNil(action.payload)) {
return {}
}
return action.payload
}
if (matchPattern(mergeById, action)) {
const { id, data } = action.payload
const newValue = F.mergeDeepLeft(data, state[id] || {})
return F.assoc(id, newValue, state)
}
if (matchPattern(updateById, action)) {
const { id, data } = action.payload
return F.assoc(id, data, state)
}
if (matchPattern(removeById, action)) {
const { id } = action.payload
return F.dissoc(id, state)
}
if (matchPattern(reset, action)) {
return INITIAL_STATE
}
return state
}
// Selectors
makeEntitiesReducer.getAsList = Object.values
makeEntitiesReducer.getOne = (id, state) => state[id]
makeEntitiesReducer.getSomeAsList = (ids, state) => ids.map(id => state[id])
makeEntitiesReducer.getSomeAsObject = (ids, state) =>
Object.fromEntries(ids.map(id => [id, state[id]]))
export default makeEntitiesReducer