Skip to content

Instantly share code, notes, and snippets.

@iAmShakil
Created August 31, 2018 17:20
Show Gist options
  • Save iAmShakil/08d096a85fa1514a370234a22061be97 to your computer and use it in GitHub Desktop.
Save iAmShakil/08d096a85fa1514a370234a22061be97 to your computer and use it in GitHub Desktop.
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(){
// getting the index of the subscriber in the subscribers array
let index = subscribers.indexOf(subscriber)
// deleting the array element using the index
subscribers.splice(index, 1)
}
}
return {
getState: getState,
dispatch: dispatch,
subscribe: subscribe
}
}
// testing the subscriber methods
const store = createStore(reducer)
const unsubscribe = 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" })
// calling unscribe will stop executing the subscriber function
unsubscribe()
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