Created
August 31, 2018 17:19
-
-
Save iAmShakil/8f28a7d92820bbd8fc4fa7cee665931e 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
const reducer = ( state = 0, action ) => { | |
switch(action.type){ | |
case "INCREMENT": | |
return state + 1 | |
case "DECREMENT": | |
return state - 1 | |
default: | |
return state | |
} | |
} | |
function createStore(reducer){ | |
var state | |
// this array contains all the subscriber functions. | |
var subscribers = [] | |
function getState(){ | |
return state | |
} | |
function dispatch(action){ | |
// passing the action and the state parameters to the reducer function. The returned value is set as state | |
state = reducer(state, action) | |
// each time the dispatch function runs, we loop through all the functions stored in the subscribers array and invoke them. | |
subscribers.forEach( (subscriber) => { | |
subscriber() | |
} ) | |
} | |
function subscribe(subscriber){ | |
// functions passed to the subscribe method are added to the subscribers array | |
subscribers.push(subscriber) | |
// invoking this returned function will remove the subscriber function | |
return function(){ | |
} | |
} | |
return { | |
getState: getState, | |
dispatch: dispatch, | |
subscribe: subscribe | |
} | |
} | |
// testing the subscriber methods | |
const store = createStore(reducer) | |
store.subscribe( () => { | |
// this function is going to be run each time dispatch is called | |
console.log("the current state is ", store.getState()) | |
} ) | |
store.dispatch({ type: "INCREMENT" }) | |
store.dispatch({ type: "INCREMENT" }) | |
store.dispatch({ type: "INCREMENT" }) | |
store.dispatch({ type: "DECREMENT" }) | |
store.dispatch({ type: "DECREMENT" }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment