Skip to content

Instantly share code, notes, and snippets.

@Goku-kun
Last active January 13, 2022 04:04
Show Gist options
  • Save Goku-kun/00deacd5cec0bb968000e35a3e427ec3 to your computer and use it in GitHub Desktop.
Save Goku-kun/00deacd5cec0bb968000e35a3e427ec3 to your computer and use it in GitHub Desktop.
This gist is a very stripped out implementation of the redux library.
function createStore(reducer) {
let state;
let subscribers = [];
function getState() {
return state;
}
function dispatch(action) {
state = reducer(state, action);
//update the state and then call each of the subscriber.
subscribers.forEach((subscriber) => subscriber());
}
function subscribe(subscriber) {
subscribers.push(subscriber);
// function to unsubscribe a particular subscribed function.
return function () {
subscribers = subscribers.filter(function (itemSubscriber) {
return subscriber !== itemSubscriber;
});
};
}
function replaceReducer(newReducer) {
// replace the original reducer
reducer = newReducer;
}
// this call to dispatch is made to initialize the state object because reducer would contain a default initial state.
dispatch({});
return { getState, dispatch, subscribe, replaceReducer };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment