Skip to content

Commit 04b15f4

Browse files
committed
fix(combineReducers): add comments and refactor code; trigger semantic-release
(semantic-release doesn't consider "perf" commits)
1 parent d5aacc8 commit 04b15f4

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/combineReducers.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,27 +9,37 @@ export default function combineReducers(reducers, createInitialState = Map) {
99
const actionHandlers = {}
1010
const otherReducers = {}
1111
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+
1218
forEach(reducers, (reducer, key) => {
1319
initialStateObj[key] = reducer(undefined, {})
1420
if (reducer.actionHandlers) {
15-
// invert from prop name -> action type -> reducer
16-
// to action type -> prop name -> reducer
1721
forEach(reducer.actionHandlers, (actionHandler, type) => {
1822
(actionHandlers[type] || (actionHandlers[type] = {}))[key] = actionHandler
1923
})
2024
} else otherReducers[key] = reducer
2125
})
2226
const initialState = createInitialState(initialStateObj)
2327

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
2432
const combineBase = reducers => {
2533
let result
2634
if (size(reducers) > 1) {
35+
// we have to update multiple keys; use state.withMutations
2736
result = (state = initialState, action) => state.withMutations(mutableState => reduce(
2837
reducers,
2938
(nextState, reducer, key) => nextState.update(key, value => reducer(value, action)),
3039
mutableState)
3140
)
3241
} else {
42+
// we only have to update one key; use state.update
3343
const key = Object.keys(reducers)[0]
3444
const reducer = reducers[key]
3545
result = (state = initialState, action) => state.update(key, value => reducer(value, action))
@@ -47,9 +57,9 @@ export default function combineReducers(reducers, createInitialState = Map) {
4757
: undefined
4858

4959
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
5363
}
5464

5565

0 commit comments

Comments
 (0)