Skip to content

Instantly share code, notes, and snippets.

@kastigar
Created November 23, 2016 12:01
Show Gist options
  • Save kastigar/c9056987df6182875e9740a7d02787ad to your computer and use it in GitHub Desktop.
Save kastigar/c9056987df6182875e9740a7d02787ad to your computer and use it in GitHub Desktop.
Higher order reducer for default case
function createReducerWithDefaultCase(decl, initial) {
const defaultCase = decl['*'];
delete decl['*'];
const reducer = createReducer(decl, initital);
if (!defaultCase) return reducer;
const declaredActions = Object.keys(decl);
return (state, action) => {
if (declaredActions.includes(action.type)) {
return reducer(state,action);
}
return defaultCase(state, action.payload);
};
}
createReducerWithDefaultCase({
[increment]: state => state + 1,
[decrement]: state => state - 1,
'*': () => 0,
}, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment