Skip to content

Instantly share code, notes, and snippets.

@jupegarnica
Forked from einatbar/createStore.js
Created May 7, 2019 06:49
Show Gist options
  • Select an option

  • Save jupegarnica/ff60420f8401fc31ecdbda9a5fc45bda to your computer and use it in GitHub Desktop.

Select an option

Save jupegarnica/ff60420f8401fc31ecdbda9a5fc45bda to your computer and use it in GitHub Desktop.
Simple Redux implementation - final
const createStore = (reducer, initialState = {}, middlewares = []) => {
let state = initialState;
const listeners = [];
// final step - call the reducer and invoke the listeners
let finalMiddleware = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
return state;
}
// the middleware API is constructed of getState and dispatch
const middlewareAPI = { getState: () => state, dispatch: (action) => finalMiddleware(action) }
// evalutate the first function in the structure of the middlewares
const newMiddleWares = middlewares.map(middleware => middleware(middlewareAPI));
// go over the new middlewares reversed and evaluate the second function in the structure
// the second function receives the third fucntion of the next middleware
// this way we can make sure that when the developer will call next(action)
// he will acually execute the next middleware's most inner funciton
for(let i = newMiddleWares.length - 1; i >= 0; i--) {
finalMiddleware = newMiddleWares[i](finalMiddleware);
}
return {
...middlewareAPI,
subscribe: (listener) => {
listeners.push(listener);
return () => {listeners.splice(listeners.indexOf(listener), 1);}}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment