function reducer(state, { type, good, count, money }) { if (!state) { let state = { пиво: { количество: 100, цена: 25, }, чипсы: { количество: 100, цена: 35, }, сиги: { количество: 100, цена: 60, }, }; let newState = {}; for (let [key, value] of Object.entries(state)) { newState[key] = ""; if (typeof value === "object") { newState[`${key}-количество`] = value["количество"]; newState[`${key}-цена`] = value["цена"]; } } return newState; } if (type === "КУПИТЬ") { if (money / count >= state[`${good}-цена`]) { if (state[`${good}-количество`] - count >= 0) { return { ...state, [`${good}-количество`]: state[`${good}-количество`] - count, }; } else { alert( `Товар '${good}' закончилось! ${ state[`${good}-количество`] !== 0 ? "Выдано остаток: " + state[`${good}-количество`] : `На складе нет остатков товара '${good}'!` }` ); return { ...state, [`${good}-количество`]: 0, }; } } else { alert( `У вас не хватает денег! Для ${count} товара '${good}' необходимо ${ state[`${good}-цена`] * count } гривнів` ); } } return state; } 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, }; } const store = createStore(reducer); const unsubscribe = store.subscribe(() => console.log(store.getState())); let buySmth = (good, count, money) => ({ type: "КУПИТЬ", good, count, money, }); for (let [key] of Object.entries(store.getState())) { if (!key.includes("-")) { let option = new Option(key); goods.append(option); } } let fields = Object.keys(store.getState()); for (let i = 0; i < fields.length; i++) { let h = document.createElement("h1"); h.id = fields[i]; h.className = "goods"; h.innerText = `${fields[i]} : ${store.getState()[fields[i]]}`; shop.append(h); } quantity.oninput = () => { if (quantity.value === "" || +quantity.value < 1) { quantity.value = 1; } }; money.oninput = () => { if (money.value === "" || +money.value < 1) { money.value = 1; } }; buy.onclick = () => { let headers = document.querySelectorAll(".goods"); for (let i = 0; i < headers.length; i++) { if (`${goods.value}-количество` === headers[i].id) { store.subscribe( () => (headers[i].innerText = `${headers[i].id} : ${ store.getState()[headers[i].id] }`) ); store.dispatch(buySmth(goods.value, quantity.value, money.value)); money.value = 1; } } }; store.getState();