Created
March 5, 2018 22:12
-
-
Save sithu/4f04d99d4ed3ccc55d3a20448e6e0553 to your computer and use it in GitHub Desktop.
Redux Example
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
| 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