Skip to content

Instantly share code, notes, and snippets.

@btmills
Created January 20, 2016 22:57
Show Gist options
  • Save btmills/a2341d254bb5d7dbbe0c to your computer and use it in GitHub Desktop.
Save btmills/a2341d254bb5d7dbbe0c to your computer and use it in GitHub Desktop.
Simple example of state, actions, and reducers
const INCREMENT = Symbol('INCREMENT');
const DECREMENT = Symbol('DECREMENT');
const makeReducer = (initialState, reducers = {}, props = {}) =>
(state = initialState, action) =>
reducers.hasOwnProperty(action.type) ? reducers[action.type](state, action) : state;
const reducer = makeReducer(42, {
[INCREMENT]: (state, action) => state + 1,
[DECREMENT]: (state, action) => state - 1
});
const makeAction = (type) => ({ type });
const run = (reducer) => (actions) => actions.reduce((state, action) => {
const next = reducer(state, action);
console.log({
previous: state,
action: action.type.toString(),
next
});
return next;
}, reducer(undefined, {}));
run(reducer)([
INCREMENT, INCREMENT, INCREMENT, DECREMENT, INCREMENT
].map(makeAction));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment