-
-
Notifications
You must be signed in to change notification settings - Fork 15.2k
Closed
Labels
Description
I really hate the huge switch, so I write a util function to help write reducer in a better way. ( My English is not that good, but I will try to show my idea. )
example
we can write like this.
import { ADD_TODO, DELETE_TODO, EDIT_TODO, COMPLETE_TODO, COMPLETE_ALL, CLEAR_COMPLETED } from '../constants/ActionTypes';
const initialState = [{
text: 'Use Redux',
completed: false,
id: 0
}];
export default createReducer({
[ADD_TODO]: (state, { text }) => [{
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
completed: false,
text
}, ...state],
[DELETE_TODO]: (state, { id }) => state.filter(todo =>
todo.id !== action.id
),
[EDIT_TODO]: (state, { id, text }) => state.map(todo =>
todo.id === id ?
Object.assign({}, todo, { text }) :
todo
),
[COMPLETE_ALL]: state => {
const areAllMarked = state.every(todo => todo.completed);
return state.map(todo => Object.assign({}, todo, {
completed: !areAllMarked
}));
},
[CLEAR_COMPLETED]: state => state.filter(todo => todo.completed === false)
}, initialState)
source code
/**
* an elegance way to write reducer
* @param funcMap the functions map
* @param initState initiate state
* @returns {Function}
*/
function createReducer(funcMap, initialState) {
if (!isPlainObject(funcMap)) {
throw new Error('funcMap need to be a plain object');
}
return (state = initState, action) => map.hasOwnProperty(action.type) ?
funcMap[action.type](state, action) :
state;
}
features
- simple, whether use or not depends on you.
- won't worry about the variable name duplicated
- can use destruct
action
andstate
- can use arrow function
- hashTable is faster than
switch
when having a lot of cases - don't need annoying
break
anddefault
segor, herlon214, sk22, nekman, yashatgit and 8 more