Skip to content

Instantly share code, notes, and snippets.

@keslo
Last active January 22, 2020 08:18
Show Gist options
  • Save keslo/806344bf5dd8f23e7c75965f0b60ae73 to your computer and use it in GitHub Desktop.
Save keslo/806344bf5dd8f23e7c75965f0b60ae73 to your computer and use it in GitHub Desktop.
function applyMiddleware(...middlewares) {
return (createStore) => (reducer, ...args) => {
const store = createStore(reducer, ...args)
let dispatch;
const middlewareAPI = {
getState: store.dispatch,
dispatch: (action, ...args) => dispatch(action, ...args)
}
const chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
function compose(...funcs) {
if (funcs.length === 0) return arg => arg
if (funcs.length === 1) return funcs[0]
return funcs.reduce( (a, b) => (...args) => a(b(...args)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment