Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type Foo = {id: number};
- const fooReducer = (state: Foo, action) => {
- switch (action) {
- case "RENAME":
- return state.id === action.id
- ? { ...state, name: action.name }
- : state;
- default: return state;
- }
- }
- const foosReducer = (state: Foo[] = [], action) => {
- switch (action) {
- case "ADD_FOO": return [...state, action.foo];
- case "RENAME": return state.map(foo => fooReducer(foo, action));
- default: return state;
- }
- }
- const alternativeFooReducer = (state: Foo, action) => {
- switch (action) {
- case "RENAME": return { ...state, name: action.name };
- default: return state;
- }
- }
- const alternativeFoosReducer = (state: Foo[] = [], action) => {
- switch (action) {
- case "ADD_FOO": return [...state, action.foo];
- case "RENAME": {
- const fooToRename = state.find(f => f.id === action.id);
- const index = state.indexOf(fooToRename);
- return [
- ...state.slice(0, index),
- alternativeFooReducer(fooToRename, action),
- ...state.slice(index + 1)
- ]
- }
- default: return state;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement