Last active
January 7, 2018 04:13
-
-
Save abiodun0/1137039e53884736cef1465df253bcb7 to your computer and use it in GitHub Desktop.
switch and object lookup redux
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
//You can use an object as a lookup table instead | |
const handlers = { | |
ADD_ITEM(state, action) { ... } | |
REMOVE_ITEM(state, action) { ... } | |
} | |
function itemReducer (state, action) { | |
if (action.type in handlers) { | |
return handlers[action.type](state, action) | |
} else { | |
return state | |
} | |
} | |
// OR | |
function createReducer (initialState, actionMap) { | |
return function reducer (state = initialState, action) { | |
if (action.type in actionMap) { | |
const result = actionMap[action.type](state, action) | |
if (result === undefined) { | |
console.warn('Reducer returned undefined for action ' + action.type + ', ignoring') | |
return state | |
} else { | |
return result | |
} | |
} else { | |
return state | |
} | |
} | |
} | |
// Then | |
const itemReducer = createReducer({ items: [] }, { | |
ADD_ITEM (state, action) { | |
return state.items.concat(action.payload) | |
}, | |
REMOVE_ITEM (state, action) { | |
return state.items.filter(it => it === action.payload) | |
} | |
}) | |
// You don’t need to introduce yet another thing to hold in your head while you learn a new system. | |
// It also reinforces that redux is just JS. There’s no magic behind what it’s doing. | |
// It’s just an asynchronous version of `listOfActions.reduce(reducer, initialState)` | |
//There’s some sort of tradeoff there for very high-performance needs (performance >= 60fps). | |
// Switch statements are somehow aggressively optimized by the VM (at least in Chrome), | |
// so are nominally faster than object lookups for reasonable numbers of case clauses. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment