Skip to content

Instantly share code, notes, and snippets.

@sithu
Created March 5, 2018 22:12
Show Gist options
  • Select an option

  • Save sithu/4f04d99d4ed3ccc55d3a20448e6e0553 to your computer and use it in GitHub Desktop.

Select an option

Save sithu/4f04d99d4ed3ccc55d3a20448e6e0553 to your computer and use it in GitHub Desktop.
Redux Example
const print = console.log;
const actions = [
{ type: 'ADD', value: 1 },
{ type: 'SUBTRACT', value: 2 },
{ type: 'ADD', value: 3 },
{ type: 'SUBTRACT', value: 4 },
{ type: 'ADD', value: 5 },
]
// 'state' a.k.a accumulator is the return value.
const reducer = (state=0, action) => {
switch (action.type) {
case 'ADD': return state + action.value;
case 'SUBTRACT': return state - action.value;
default: return state;
}
};
const createStore = (reducer) => {
let currentState = {};
const subcriptions = [];
return {
getState: () => currentState,
dispatch: action => {
currentState = reducer(currentState, action);
subcriptions.forEach(fn => fn());
},
subscribe: fn => subcriptions.push(fn),
};
};
const finalState = actions.reduce(reducer, undefined);
print(finalState);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment