Eliminate switch statements for better code structure
- Code evolution 1: Pure switch
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
Copy the code
- Use the ternary operator instead
const counter = (state = 0, action) =>
action.type === 'INCREMENT' ? state + 1
: action.type === 'DECREMENT' ? state - 1
: state
Copy the code
- Replace action.type === with the object’s own method
function switchcase (cases, defaultCase, key) {
if (cases.hasOwnProperty(key)) {
return cases[key]
} else {
return defaultCase
}
}
Copy the code
- Currie,
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)
Copy the code
- Added function detection
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))
Copy the code
- Switch app — Sunday conversion
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()
Copy the code
Eliminate switch for better code structure