Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save factoryhr/fa6bb268c0e427ea7a949e9874a2a1be to your computer and use it in GitHub Desktop.
Save factoryhr/fa6bb268c0e427ea7a949e9874a2a1be to your computer and use it in GitHub Desktop.
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