123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- 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, price: 30},
- чипсы: {count: 100, price: 25},
- сиги: {count: 100, price: 50},
- касса: 0,
- }
- }
- if (type === 'КУПИТЬ' &&
- state[ШО] && СКОКА > 0 &&
- СКОКА <= state[ШО].count && БАБОС >= state[ШО].price){
-
-
-
-
-
- console.log('bang')
- console.log(store.getState())
- state.касса += +БАБОС
- return {
- ...state,
- [ШО]: {count: state[ШО].count - Math.floor(СКОКА), price: state[ШО].price },
-
- }
- }
- return state
- }
- const store = createStore(reducer)
- let select = document.getElementById('goods')
- for(let key in store.getState()) {
- if (key === 'касса') continue;
- let option = document.createElement('option')
- option.innerText = key
- option.value = key
- select.append(option)
- }
- let quantity = document.getElementById('quantity')
- let cash = document.getElementById('cash')
- const купи = (ШО, СКОКА, БАБОС) => ({type: 'КУПИТЬ', ШО, СКОКА, БАБОС})
- buy.onclick = () => {
-
- store.dispatch(купи(select.value, quantity.value, cash.value))
- console.log('steit', store.getState())
- }
- const unsubscribe = store.subscribe(() => console.log(store.getState()))
- let table = document.createElement('table')
- function drawTable(){
- table.innerHTML = ''
- table.insertAdjacentHTML('afterbegin', `
- <tr>
- <th>Товар</th>
- <th>Кол-во</th>
- <th>Стоимость</th>
- </tr>
- `)
-
- for(let key in store.getState()) {
- if(key === 'касса') continue;
- let tr = document.createElement('tr')
- let tdKey = document.createElement('td')
- let tdCount = document.createElement('td')
- let tdCost = document.createElement('td')
- tdKey.innerText = key
- tdCount.innerText = store.getState()[key].count
- tdCost.innerText = `${store.getState()[key].price} денег`
- tr.append(tdKey, tdCount, tdCost)
- table.append(tr)
- }
- table.insertAdjacentHTML('beforeend', `
- <tr>
- <th>Касса</th>
- <td>${store.getState().касса}</td>
- </tr>
- `)
- shop.append(table)
- }
- drawTable()
- store.subscribe(drawTable)
- console.log(store.getState())
|