Skip to content

Instantly share code, notes, and snippets.

@sebjwallace
Last active May 25, 2022 06:44
Show Gist options
  • Save sebjwallace/3a1c9cb9e64f3c80da84 to your computer and use it in GitHub Desktop.
Save sebjwallace/3a1c9cb9e64f3c80da84 to your computer and use it in GitHub Desktop.
Redux reducer using object literal instead of a switch statement
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' });
@nk1tz
Copy link

nk1tz commented Oct 4, 2018

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']);

@SpaceCowboy20
Copy link

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?

@sebjwallace
Copy link
Author

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