@@ -9,27 +9,37 @@ export default function combineReducers(reducers, createInitialState = Map) {
9
9
const actionHandlers = { }
10
10
const otherReducers = { }
11
11
const initialStateObj = { }
12
+
13
+ // regroup reducers that have actionHandlers:
14
+ // from: prop name -> action type -> reducer
15
+ // to: action type -> prop name -> reducer
16
+ // put reducers without actionHandlers into a prop name -> reducer map
17
+
12
18
forEach ( reducers , ( reducer , key ) => {
13
19
initialStateObj [ key ] = reducer ( undefined , { } )
14
20
if ( reducer . actionHandlers ) {
15
- // invert from prop name -> action type -> reducer
16
- // to action type -> prop name -> reducer
17
21
forEach ( reducer . actionHandlers , ( actionHandler , type ) => {
18
22
( actionHandlers [ type ] || ( actionHandlers [ type ] = { } ) ) [ key ] = actionHandler
19
23
} )
20
24
} else otherReducers [ key ] = reducer
21
25
} )
22
26
const initialState = createInitialState ( initialStateObj )
23
27
28
+ // now we can create a more efficient reducer for each action type
29
+ // and one more efficient reducer for the otherReducers
30
+
31
+ // creates an efficient reducer from a prop name -> reducer map
24
32
const combineBase = reducers => {
25
33
let result
26
34
if ( size ( reducers ) > 1 ) {
35
+ // we have to update multiple keys; use state.withMutations
27
36
result = ( state = initialState , action ) => state . withMutations ( mutableState => reduce (
28
37
reducers ,
29
38
( nextState , reducer , key ) => nextState . update ( key , value => reducer ( value , action ) ) ,
30
39
mutableState )
31
40
)
32
41
} else {
42
+ // we only have to update one key; use state.update
33
43
const key = Object . keys ( reducers ) [ 0 ]
34
44
const reducer = reducers [ key ]
35
45
result = ( state = initialState , action ) => state . update ( key , value => reducer ( value , action ) )
@@ -47,9 +57,9 @@ export default function combineReducers(reducers, createInitialState = Map) {
47
57
: undefined
48
58
49
59
if ( actionHandlerReducer && otherReducer ) return composeReducers ( actionHandlerReducer , otherReducer )
50
- else if ( actionHandlerReducer ) return actionHandlerReducer
51
- else if ( otherReducer ) return otherReducer
52
- else return ( state = initialState ) => state
60
+ if ( actionHandlerReducer ) return actionHandlerReducer
61
+ if ( otherReducer ) return otherReducer
62
+ return ( state = initialState ) => state
53
63
}
54
64
55
65
0 commit comments