Skip to content

Commit

Permalink
✨ utils functions
Browse files Browse the repository at this point in the history
- compose
- applyMiddleware
  • Loading branch information
d2FuZ3h1ZG9uZw committed Mar 15, 2022
1 parent ed7b776 commit 68a7f6a
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 2 deletions.
27 changes: 26 additions & 1 deletion lib/applyMiddleware.js
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
// TODO
import compose from './compose'

/**
* applyMiddleware is a function produce(return) enhancer function
* middleware only can extend the dispatch
* @param {...any} middlewares
*/
export default (...middlewares) => {
return createStore =>
(...args) => {
const store = createStore(...args)

const middlewareAPI = {
getState: store.getState
// dispatch: (...args) => dispatch(args)
}

const chain = middlewares.map(middleware => middleware(middlewareAPI))
const dispatch = compose(...chain)(store.dispatch)

return {
...store,
dispatch
}
}
}
15 changes: 15 additions & 0 deletions lib/compose.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
*
* @param {...any} funcs
* @returns
*/
export default (...funcs) => {
if (funcs.length === 0) return arg => arg
if (funcs.length === 1) return funcs[0]

return funcs.reduce(
(a, b) =>
(...args) =>
a(b(...args))
)
}
2 changes: 1 addition & 1 deletion lib/createStore.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @ts-check

// @ts-ignore
import { isPlainObject, ActionTypes, error } from 'utils'
import { isPlainObject, ActionTypes, error } from './utils'

// TODO subscribe while dispatch something...

Expand Down
5 changes: 5 additions & 0 deletions lib/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createStore } from './createStore'
import compose from './compose'
import applyMiddleware from './applyMiddleware'

export { createStore, compose, applyMiddleware }

0 comments on commit 68a7f6a

Please sign in to comment.