const createStore = function (reducer, initState = {}) {
let state = initState;
let listeners = [];
function getState() {
return state;
}
function subscribe(fn) {
listeners.push(fn)
return function () {
let index = listeners.indexOf(fn);
listeners.splice(index, 1);
}
}
function dispatch(action) {
state = reducer(state, action);
console.log('state,dispatch', reducer);
for (let i = 0; i < listeners.length; i++) {
listeners[i]();
}
}
dispatch({ type: Symbol() })
return {
state,
subscribe,
getState,
dispatch
}
}
function reducer(newState, action) {
switch (action.type) {
case ‘update’:
return {
…newState,
…action.payload
}
case ‘onRefresh’:
return {
…newState
}
default:
return { …newState }
}
}
function countReducer(state, action) {
if (!state) {
state = {
count: 1
}
}
switch (action.type) {
case ‘increment’:
return {
count: state.count + 1
}
case ‘decrement’:
return {
count: state.count - 1
}
default:
return { …state }
}
}
function infoReducer(state, action) {
if (!state) {
state = {
name: ‘’,
desc: ‘’
}
}
switch (action.type) {
case ‘update’:
return {
…state, …action.payload
}
default:
return {
…state
}
}
}
function combineReducer(reducers) {
return function (state, action) {
return Object.keys(reducers).reduce((nextState, key) => {
nextState[key] = reducers[key](state[key], action);
return nextState
}, {})
}
}
let store = createStore(combineReducer({ counter: countReducer, info: infoReducer }));
store.subscribe(() => {
let state = store.getState();
console.log(‘state’, state);
console.log(i am ${state.counter.count},and ${state.info.desc}
);
})
store.dispatch({
type: ‘increment’
})