Last active
May 25, 2022 06:44
-
-
Save sebjwallace/3a1c9cb9e64f3c80da84 to your computer and use it in GitHub Desktop.
Redux reducer using object literal instead of a switch statement
This file contains 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
import {createStore} from 'redux'; | |
const counter = (state = 0, action) => { | |
const index = { | |
'INCREMENT': () => { | |
return state+1; | |
}, | |
'DECREMENT': () => { | |
return state-1; | |
}, | |
'DEFAULT': () => { | |
return state; | |
} | |
}; | |
return (index[action.type] || index['DEFAULT'])(); | |
} | |
const store = createStore(counter); | |
store.subscribe( () => { console.log(store.getState()); } ); | |
store.dispatch({ type: 'INCREMENT' }); | |
store.dispatch({ type: 'DECREMENT' }); |
Hi @sebjwallace
Quick question for you my friend :)
I am using the same technique, and I'm wondering if there is a good reason to make each property of
index
a function. Is this a way of obtaining immutability? I'm not sure why it is necessary, is the following identical? :const counter = (state = 0, action) => ({ 'INCREMENT': state+1; 'DECREMENT': state-1; 'DEFAULT': state; }[action.type] || 'DEFAULT']);
Did you try it? did it work?
That should work fine @SpaceCowboy20, but the syntax should be corrected:
const counter = (state = 0, action) => ({
'INCREMENT': state+1,
'DECREMENT': state-1,
'DEFAULT': state
}[action.type || 'DEFAULT'])
The downside of this approach is that all three attributes are being computed, but only one will be used. Only a concern if performance is a concern.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @sebjwallace
Quick question for you my friend :)
I am using the same technique, and I'm wondering if there is a good reason to make each property of
index
a function.Is this a way of obtaining immutability? I'm not sure why it is necessary, is the following identical? :