Created
August 31, 2018 17:18
-
-
Save iAmShakil/c0941c3a3f3902ede4e3f22e95b624f1 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){ | |
// declaring the variable that holds state of the store | |
var state | |
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) | |
} | |
function subscribe(){ | |
// invoking this returned function will remove the subscriber function | |
return function(){ | |
} | |
} | |
return { | |
getState: getState, | |
dispatch: dispatch, | |
subscribe: subscribe | |
} | |
} | |
// testing the dispatch method | |
const store = createStore(reducer) | |
// this should set the state to 1 | |
store.dispatch({ type: "INCREMENT" }) | |
console.log(store.getState()) | |
// this should set the state back to 0 | |
store.dispatch({ type: "DECREMENT" }) | |
console.log(store.getState()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment