Skip to content

Instantly share code, notes, and snippets.

@ZacharyL2
Created July 10, 2022 12:00
Show Gist options
  • Save ZacharyL2/2721d0ff4ef3912c9f18fad348220744 to your computer and use it in GitHub Desktop.
Save ZacharyL2/2721d0ff4ef3912c9f18fad348220744 to your computer and use it in GitHub Desktop.
// Serial execution of multiple functions
const compose = (...funcs) =>
funcs.reduce(
(a, b) =>
(...args) =>
a(b(...args)),
);
export const createStore = (reducer, enhancer) => {
if (typeof enhancer === 'function') {
return enhancer(createStore)(reducer);
}
let state;
const listeners = [];
const subscribe = (callback) => {
listeners.push(callback);
};
const dispatch = (action) => {
state = reducer(state, action);
for (const listener of listeners) {
listener();
}
};
const getState = () => state;
const store = {
subscribe,
dispatch,
getState,
};
return store;
};
export const combineReducers =
(reducers) =>
(state = {}, action) => {
const nextState = {};
for (const [key, reducer] of Object.entries(reducers)) {
const previousStateForKey = state[key];
const nextStateForKey = reducer(previousStateForKey, action);
nextState[key] = nextStateForKey;
}
return nextState;
};
export const applyMiddleware =
(...middlewares) =>
(create) =>
(reducer) => {
const store = create(reducer);
const chain = middlewares.map((middleware) => middleware(store));
// Enhanced dispatch
return { ...store, dispatch: compose(...chain)(store.dispatch) };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment