Skip to content

Commit

Permalink
Refactor combineReduer's Unexpected State Shape Warning
Browse files Browse the repository at this point in the history
The shape of the previous state is irrelevant, what we’re actually
testing is that state has the same shape as our reducer object
`finalReducers`.

Also fixes the algorithm to be O(n) by using `#hasOwnProperty` vs doing
an array search.
  • Loading branch information
jridgewell committed Dec 12, 2015
1 parent 683dc38 commit e5aabde
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions src/utils/combineReducers.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ function getUndefinedStateErrorMessage(key, action) {
)
}

function getUnexpectedStateKeyWarningMessage(inputState, outputState, action) {
var reducerKeys = Object.keys(outputState)
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
var reducerKeys = Object.keys(reducers)
var argumentName = action && action.type === ActionTypes.INIT ?
'initialState argument passed to createStore' :
'previous state received by the reducer'
Expand All @@ -37,9 +37,7 @@ function getUnexpectedStateKeyWarningMessage(inputState, outputState, action) {
)
}

var unexpectedKeys = Object.keys(inputState).filter(
key => reducerKeys.indexOf(key) < 0
)
var unexpectedKeys = Object.keys(inputState).filter(key => !reducers.hasOwnProperty(key))

if (unexpectedKeys.length > 0) {
return (
Expand Down Expand Up @@ -106,13 +104,18 @@ export default function combineReducers(reducers) {
sanityError = e
}

var defaultState = mapValues(finalReducers, () => undefined)

return function combination(state = defaultState, action) {
return function combination(state = {}, action) {
if (sanityError) {
throw sanityError
}

if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action)
if (warningMessage) {
console.error(warningMessage)
}
}

var hasChanged = false
var finalState = mapValues(finalReducers, (reducer, key) => {
var previousStateForKey = state[key]
Expand All @@ -125,13 +128,6 @@ export default function combineReducers(reducers) {
return nextStateForKey
})

if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateKeyWarningMessage(state, finalState, action)
if (warningMessage) {
console.error(warningMessage)
}
}

return hasChanged ? finalState : state
}
}

0 comments on commit e5aabde

Please sign in to comment.