function createStore(reducer) { let state = reducer(undefined, {}); let cbs = []; const getState = () => state; const subscribe = cb => (cbs.push(cb), () => cbs = cbs.filter(c => c !== cb)); const dispatch = action => { const newState = reducer(state, action); if (newState !== state) { state = newState; for (let cb of cbs) cb(); } }; return { getState, dispatch, subscribe }; } function reducer(state, {type, ШО, СКОКА}) { if (!state) { return { пиво: { count: 100, priceForOne: 6, }, чипсы: { count: 100, priceForOne: 14, }, сиги: { count: 100, priceForOne: 25, }, касса: { count: 0, }, деньги: { count: 0 } }; } if (type === 'КУПИТЬ') { for (let key in {...state}) { if (key === ШО && (СКОКА) > {...state}[key].count) { return state; } } const total = +СКОКА * state[ШО].priceForOne; if(state.деньги.count >= total){ return { ...state, касса: {count: state.касса.count + total}, деньги: {count: state.деньги.count - total}, [ШО]: {...state[ШО], count: state[ШО].count - +СКОКА}, }; } } if(type === 'МоиДеньги'){ return { ...state, деньги: {count: +СКОКА} } } return state; } const store = createStore(reducer); for (let key in store.getState()) { let goods = document.getElementById('goods'); let option = document.createElement('option'); option.innerHTML = key; goods.appendChild(option); } const купи = (ШО, СКОКА) => ({type: 'КУПИТЬ', ШО, СКОКА}); const моиДеньги = (СКОКА) => ({type: 'МоиДеньги', СКОКА}); let buy = document.getElementById('buy'); buy.onclick = () => { let goods = document.getElementById('goods'); let quantity = document.getElementById('quantity'); store.dispatch(купи(goods.value, quantity.value)); }; fieldForMoney.oninput = (event) => { store.dispatch(моиДеньги(event.target.value)); } const unsubscribe = store.subscribe(() => console.log(store.getState())); setTimeout(unsubscribe, 1000); store.subscribe( () => { fieldForMoney.value = store.getState().деньги.count; }) function createTable() { const shop = document.getElementById('shop'); let table = document.createElement('table'); let tr = document.createElement('tr'); let tr1 = document.createElement('tr'); let tr2 = document.createElement('tr'); for (let key in store.getState()) { let th = document.createElement('th'); th.innerText = key; let td1 = document.createElement('td'); td1.innerText = store.getState()[key].count; let td2 = document.createElement('td'); td2.innerText = store.getState()[key].priceForOne || ''; tr2.appendChild(td2); tr1.appendChild(td1); tr.appendChild(th); store.subscribe(() => { td1.innerText = store.getState()[key].count; }); td1.innerText = store.getState()[key].count; } table.appendChild(tr); table.appendChild(tr1); table.appendChild(tr2); shop.append(table); } createTable(); setTimeout(() => store.dispatch({type: 'купить', ШО: 'пиво', СКОКА: 3}), 1000);