Last active
August 8, 2017 12:00
-
-
Save dan-tenovski/90fe0e03a9c908a4620035d504980002 to your computer and use it in GitHub Desktop.
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
// reducer.js | |
let initialState = 0; | |
function reducer (state=initialState, action) { | |
switch(action.type){ | |
case 'INCREMENT_COUNT': | |
return state + 1; | |
default: | |
return state | |
} | |
} | |
// store.js | |
function createStore(reducer, localState){ | |
let state = localState; | |
let subscribers = []; | |
function getState(){ | |
return state; | |
} | |
function subscribe(cb){ | |
subscribers.push(cb); | |
} | |
function dispatch(action){ | |
state = reducer(state, action); | |
subscribers.forEach((sub)=>sub()); | |
} | |
return {getState, subscribe, dispatch} | |
} | |
let reducer = require(./reducer); | |
let store = createStore(reducer, 0); | |
store.subscribe(()=>console.log(`current state ${store.getState()}`)); | |
console.log(store.getState()); // logs out 0 | |
store.dispatch({type: 'INCREMENT_COUNT'}); // logs out 1 | |
store.dispatch({type: 'INCREMENT_COUNT'}); // logs out 2 | |
store.dispatch({type: 'INCREMENT_COUNT'}); // logs out 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment