生活随笔
收集整理的這篇文章主要介紹了
消除switch语句以获得更好的代码结构
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
消除switch語句以獲得更好的代碼結構
function counter(state = 0, action) {switch (action.type) {
case 'INCREMENT':
return state 1
case 'DECREMENT':
return state - 1default:
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] : defaultCaseconst 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() : fconst switchcase = cases => defaultCase => key =>cases.hasOwnProperty(key) ? cases[key] : defaultCaseconst 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] : defaultCaseconst 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獲得更好的代碼結構(英文文檔-需翻墻)
更多專業前端知識,請上
【猿2048】www.mk2048.com
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的消除switch语句以获得更好的代码结构的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。