Created
March 27, 2018 06:40
-
-
Save factoryhr/fa6bb268c0e427ea7a949e9874a2a1be 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
function createStore(reducer, preloadedState) { | |
var currentState = preloadedState; | |
var listeners = []; | |
function getState() { | |
return currentState; | |
} | |
function subscribe(listener) { | |
listeners.push(listener); | |
return function unsubscribe() { | |
var index = listeners.indexOf(listener); | |
listeners.splice(index, 1); | |
}; | |
} | |
// Dispatch action to store | |
function dispatch(action) { | |
currentState = reducer(currentState, action); | |
for (var i = 0; i < listeners.length; i++) { | |
listeners[i](); | |
} | |
} | |
// Execute reducer for the first time | |
dispatch({ type: '__INIT__' }); | |
return { | |
getState: getState, | |
subscribe: subscribe, | |
// Expose the API | |
dispatch: dispatch, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment