Skip to content

Instantly share code, notes, and snippets.

@ZhihaoLau
Created June 5, 2016 07:44
Show Gist options
  • Save ZhihaoLau/f233c25e57795808af6b7818b261dd5b to your computer and use it in GitHub Desktop.
Save ZhihaoLau/f233c25e57795808af6b7818b261dd5b to your computer and use it in GitHub Desktop.
implement Redux's combineReducers from scratch
// accept a array of reducers
const combineReducers = (reducers) => {
// returns a huge reducer, looks like below gist
return (state = {}, action) => {
return Object.keys(reducers).reduce(
(nextState, key) => {
nextState[key] = reducers[key](
state[key],
action
)
return nextState
},
{}
)
}
}
// a huge reducer looks like this
const todoApp = (state = {}, action) => {
// 'huge reducer also returns a huge state'
return {
todos: todosReducer(
state.todos,
action
),
visibilityFilter: VisibilityFilter(
state.visibilityFilter,
action
)
}
}
@ZhihaoLau
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment