Created
August 22, 2018 09:57
-
-
Save iamandrewluca/b287a73361e88c5d188c20e5eee0bb0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// an alternative to combineReducers | |
// attach an reducer to a key in the state | |
export function attachNestedReducers(original, reducers) { | |
const nestedReducerKeys = Object.keys(reducers) | |
return function combination(state, action) { | |
const nextState = original(state, action) | |
let hasChanged = false | |
const nestedState = {} | |
for (let i = 0; i < nestedReducerKeys.length; i++) { | |
const key = nestedReducerKeys[i] | |
const reducer = reducers[key] | |
const previousStateForKey = nextState[key] | |
const nextStateForKey = reducer(previousStateForKey, action) | |
nestedState[key] = nextStateForKey | |
hasChanged = hasChanged || nextStateForKey !== previousStateForKey | |
} | |
return hasChanged ? Object.assign({}, nextState, nestedState) : nextState | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment