Created
May 10, 2019 10:15
-
-
Save hoangtranson/c3710aba2887388a68e8e5873666a9ca to your computer and use it in GitHub Desktop.
re-thinking switch code
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
function counter(state = 0, action) { | |
switch (action.type) { | |
case 'INCREMENT': | |
return state + 1 | |
case 'DECREMENT': | |
return state - 1 | |
default: | |
return state | |
} | |
} | |
//change to | |
const counter = (state = 0, action) => | |
action.type === 'INCREMENT' ? state + 1 | |
: action.type === 'DECREMENT' ? state - 1 | |
: state | |
// change to | |
const switchcase = cases => defaultCase => key => | |
cases.hasOwnProperty(key) ? cases[key] : defaultCase | |
const counter = (state = 0, action) => | |
switchcase({ | |
'INCREMENT': state + 1, | |
'DECREMENT': state -1 | |
})(state)(action.type) | |
// change to | |
const switchcaseF = cases => defaultCase => key => | |
switchcase(cases)(defaultCase)(key)() | |
const counter = (state = 0, action) => | |
switchcaseF({ | |
'INCREMENT': () => state + 1, | |
'DECREMENT': () => state -1 | |
})(() => state)(action.type) | |
// change to | |
const executeIfFunction = f => | |
f instanceof Function ? f() : f | |
const switchcaseF = cases => defaultCase => key => | |
executeIfFunction(switchcase(cases)(defaultCase)(key)) | |
const counter = (state = 0, action) => | |
switchcaseF({ | |
'INCREMENT': () => state + 1, | |
'DECREMENT': () => state -1 | |
})(state)(action.type) | |
const counter = (state = 0, action) => | |
switchcaseF({ | |
'RESET': 0, | |
'INCREMENT': () => state + 1, | |
'DECREMENT': () => state -1 | |
})(state)(action.type) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
then we can use this like: