Skip to content

Commit

Permalink
fix(combineReducers): add comments and refactor code; trigger semanti…
Browse files Browse the repository at this point in the history
…c-release

(semantic-release doesn't consider "perf" commits)
  • Loading branch information
jedwards1211 committed Mar 15, 2017
1 parent d5aacc8 commit 04b15f4
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/combineReducers.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,37 @@ export default function combineReducers(reducers, createInitialState = Map) {
const actionHandlers = {}
const otherReducers = {}
const initialStateObj = {}

// regroup reducers that have actionHandlers:
// from: prop name -> action type -> reducer
// to: action type -> prop name -> reducer
// put reducers without actionHandlers into a prop name -> reducer map

forEach(reducers, (reducer, key) => {
initialStateObj[key] = reducer(undefined, {})
if (reducer.actionHandlers) {
// invert from prop name -> action type -> reducer
// to action type -> prop name -> reducer
forEach(reducer.actionHandlers, (actionHandler, type) => {
(actionHandlers[type] || (actionHandlers[type] = {}))[key] = actionHandler
})
} else otherReducers[key] = reducer
})
const initialState = createInitialState(initialStateObj)

// now we can create a more efficient reducer for each action type
// and one more efficient reducer for the otherReducers

// creates an efficient reducer from a prop name -> reducer map
const combineBase = reducers => {
let result
if (size(reducers) > 1) {
// we have to update multiple keys; use state.withMutations
result = (state = initialState, action) => state.withMutations(mutableState => reduce(
reducers,
(nextState, reducer, key) => nextState.update(key, value => reducer(value, action)),
mutableState)
)
} else {
// we only have to update one key; use state.update
const key = Object.keys(reducers)[0]
const reducer = reducers[key]
result = (state = initialState, action) => state.update(key, value => reducer(value, action))
Expand All @@ -47,9 +57,9 @@ export default function combineReducers(reducers, createInitialState = Map) {
: undefined

if (actionHandlerReducer && otherReducer) return composeReducers(actionHandlerReducer, otherReducer)
else if (actionHandlerReducer) return actionHandlerReducer
else if (otherReducer) return otherReducer
else return (state = initialState) => state
if (actionHandlerReducer) return actionHandlerReducer
if (otherReducer) return otherReducer
return (state = initialState) => state
}


0 comments on commit 04b15f4

Please sign in to comment.