Skip to content

take away the huge switch block #883

@yeatszhang

Description

@yeatszhang

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 and state
  • can use arrow function
  • hashTable is faster than switch when having a lot of cases
  • don't need annoying break and default

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions