const createStore = (reducer,presetState, enhancer) => {
if (typeof presetState === "function") {
enhancer = presetState
presetState = undefined
}
if (typeof enhancer === 'function') {
return enhancer(createStore)(reducer,presetState)
}
if (typeof reducer !== "function") {
throw new Error('传入的reducer不是一个函数')
}
let state = presetState
let listeners = []
const getState = () => state
const dispatch = (action) => {
state = reducer(state, action)
listeners.forEach(item => item())
}
const subscribe = (fn) => {
listeners.push(fn)
}
dispatch({type:'@@react/Init'})
return {
getState,
dispatch,
subscribe
}
}