Skip to content

Instantly share code, notes, and snippets.

@iamandrewluca
Created August 22, 2018 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamandrewluca/b287a73361e88c5d188c20e5eee0bb0f to your computer and use it in GitHub Desktop.
Save iamandrewluca/b287a73361e88c5d188c20e5eee0bb0f to your computer and use it in GitHub Desktop.
// 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