Last active
June 5, 2023 04:50
-
-
Save moimikey/b6e7a1540837cc00fa32 to your computer and use it in GitHub Desktop.
object literals for redux reducers
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
// O(1) | |
const todo = (state, action) => { | |
const actions = { | |
ADD_TODO: () => { | |
return { | |
id: action.id, | |
text: action.text, | |
completed: false | |
} | |
}, | |
TOGGLE_TODO: () => { | |
if (state.id !== action.id) return state | |
return { | |
...state, | |
completed: !state.completed | |
} | |
} | |
} | |
return { | |
default: state, | |
...actions | |
}[action.type || 'default'] | |
} |
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
// O(n) | |
const todo = (state, action) => { | |
switch (action.type) { | |
case 'ADD_TODO': | |
return { | |
id: action.id, | |
text: action.text, | |
completed: false | |
} | |
case 'TOGGLE_TODO': | |
if (state.id !== action.id) { | |
return state | |
} | |
return { | |
...state, | |
completed: !state.completed | |
} | |
default: | |
return state | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is super helpful and readable. Thanks 😊