function reducer(state=1,action){
    console.log(action)
    switch(action.type){
        case "add":
            return state+1
        case "minus":
            return state-1
        case "asyncAdd":
            return state +10
    }
}



function createStore(reducer,enhancer){
    
    if(enhancer){
       return enhancer(createStore)(reducer)
    }
    let currentState=1
    let listeners=[]
    function getState(){
        return currentState
    }
    function dispatch(action){
        console.log('dispatch',action)
        currentState=reducer(currentState,action)
        listeners.map(cb=>cb())
        return action
    }
    function subscribe(cb){
        listeners.push(cb)
        console.log(listeners)
    }
    return {
        getState,
        dispatch,
        subscribe
    }
}
function applyMiddleware(...middlewares){
    return createStore=>(...args)=>{
        console.log('args',args)
        const store=createStore(...args)
        let dispatch=store.dispatch
        const midApi={
            getState:store.getState,
            dispatch
        }
        const middleChain=middlewares.map(mw=>mw(midApi))
        dispatch=compose(...middleChain)(store.dispatch)
        return{
            ...store,
            dispatch
        }
    }

}
 
const thunk = ({dispatch, getState}) => dispatch => action=> {
  if (typeof action == 'function') {
    return action(dispatch, getState)
}
  return dispatch(action)
}

 
function compose(...funcs){
    return funcs.reduce((left,right)=>(...args)=>right(left(...args)))
}
export const store=createStore(reducer,applyMiddleware(thunk))

WARRIOR
25 声望3 粉丝