Skip to content

Instantly share code, notes, and snippets.

@dan-tenovski
Last active August 8, 2017 12:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan-tenovski/90fe0e03a9c908a4620035d504980002 to your computer and use it in GitHub Desktop.
Save dan-tenovski/90fe0e03a9c908a4620035d504980002 to your computer and use it in GitHub Desktop.
// 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