消除switch语句以获得更好的代码结构
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
复制代码
const counter = (state = 0, action) =>
action.type === 'INCREMENT' ? state + 1
: action.type === 'DECREMENT' ? state - 1
: state
复制代码
- 更换action.type ===,用对象本身的方法
function switchcase (cases, defaultCase, key) {
if (cases.hasOwnProperty(key)) {
return cases[key]
} else {
return defaultCase
}
}
复制代码
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)
复制代码
const action = {
type: 'INCREMENT'
}
const executeIfFunction = f =>
f instanceof Function ? f() : f
const switchcase = cases => defaultCase => key =>
cases.hasOwnProperty(key) ? cases[key] : defaultCase
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)
console.log(counter(0, action))
复制代码
const switchcase = cases => defaultCase => key =>
cases.hasOwnProperty(key) ? cases[key] : defaultCase
const getDay = switchcase({
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
})('Unknown')
const getCurrentDay = () => getDay(new Date().getDay())
const day = getCurrentDay()
复制代码
参考链接---消除switch获得更好的代码结构(英文文档-需翻墙)