Created
November 23, 2016 12:01
-
-
Save kastigar/c9056987df6182875e9740a7d02787ad to your computer and use it in GitHub Desktop.
Higher order reducer for default case
This file contains hidden or 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
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