function createStore(reducer) {
let currentState;
let currentListeners = []
// get
function getState() {
return currentState
}
// set
function dispatch(action) {
currentState = reducer(currentState, action);
currentListeners.forEach(listener => listener());
return action;
}
// 订阅和取消订阅必须成对出现
function subscribe(listener) {
currentListeners.push(listener);
return () => {
currentListeners = currentListeners.filter(_fn => _fn !==listener)
}
}
return {
getState,
dispatch,
subscribe
}
}