Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. type Foo = {id: number};
  2.  
  3. const fooReducer = (state: Foo, action) => {
  4.     switch (action) {
  5.         case "RENAME":
  6.             return state.id === action.id
  7.                 ? { ...state, name: action.name }
  8.                 : state;
  9.         default: return state;
  10.     }
  11. }
  12.  
  13. const foosReducer = (state: Foo[] = [], action) => {
  14.     switch (action) {
  15.         case "ADD_FOO": return [...state, action.foo];
  16.         case "RENAME": return state.map(foo => fooReducer(foo, action));
  17.         default: return state;
  18.     }
  19. }
  20.  
  21. const alternativeFooReducer = (state: Foo, action) => {
  22.     switch (action) {
  23.         case "RENAME": return { ...state, name: action.name };
  24.         default: return state;
  25.     }
  26. }
  27.  
  28. const alternativeFoosReducer = (state: Foo[] = [], action) => {
  29.     switch (action) {
  30.         case "ADD_FOO": return [...state, action.foo];
  31.         case "RENAME": {
  32.             const fooToRename = state.find(f => f.id === action.id);
  33.             const index = state.indexOf(fooToRename);
  34.             return [
  35.                 ...state.slice(0, index),
  36.                 alternativeFooReducer(fooToRename, action),
  37.                 ...state.slice(index + 1)
  38.             ]
  39.         }
  40.         default: return state;
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement