hw13.js 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. function reducer(state, {type, ШО, СКОКА, БАБЛО}){
  2. if (!state){
  3. return {
  4. пиво: {
  5. колличество: 100,
  6. цена: 52
  7. },
  8. сиги: {
  9. колличество: 200,
  10. цена: 86
  11. },
  12. чипсы: {
  13. колличество: 50,
  14. цена: 43
  15. },
  16. ЧЕК: 0,
  17. СДАЧА: 0,
  18. КАССА: 0,
  19. }
  20. }
  21. switch({type, ШО, СКОКА, БАБЛО}.type) {
  22. case 'КУПИТЬ':
  23. return {
  24. ...state,
  25. [ШО]: {...state[ШО], колличество: state[ШО].колличество >= СКОКА ? state[ШО].колличество - СКОКА : (state.ЧЕК = 0) || state[ШО].колличество},
  26. КАССА: state.ЧЕК <= БАБЛО ? state.ЧЕК : 0,
  27. СДАЧА: (БАБЛО >= state.ЧЕК) ? БАБЛО - state.ЧЕК : turningIn.value = 'Не хватает БАБЛА!'
  28. }
  29. case 'СУММА ПОКУПКИ':
  30. return {
  31. ...state,
  32. ЧЕК: state[ШО].цена * СКОКА,
  33. }
  34. default:
  35. return state
  36. }
  37. }
  38. function createStore(reducer){
  39. let state = reducer(undefined, {})
  40. let cbs = []
  41. const getState = () => state
  42. const subscribe = cb => (cbs.push(cb), () => cbs = cbs.filter(c => c !== cb))
  43. const dispatch = action => {
  44. const newState = reducer(state, action)
  45. if (newState !== state){
  46. state = newState
  47. for (let cb of cbs) cb()
  48. }
  49. }
  50. return {
  51. getState,
  52. dispatch,
  53. subscribe
  54. }
  55. }
  56. function createAction (){
  57. return {
  58. type: 'КУПИТЬ',
  59. ШО: selectProduct.value,
  60. СКОКА: +countGoods.value,
  61. БАБЛО: +moneys.value,
  62. }
  63. }
  64. const kiosk = reducer(undefined, {})
  65. const store = createStore(reducer)
  66. for (let i = 0; i < Object.keys(kiosk).length; i ++) {
  67. if (typeof Object.values(kiosk)[i] === 'object') {
  68. selectProduct.appendChild(document.createElement('option')).innerHTML = Object.keys(kiosk)[i]
  69. }
  70. }
  71. beerCount.value = kiosk.пиво.колличество
  72. sigiCount.value = kiosk.сиги.колличество
  73. chipsCount.value = kiosk.чипсы.колличество
  74. store.subscribe( () => beerCount.value = store.getState().пиво.колличество, beer.innerHTML += ` ${store.getState().пиво.цена} UAH/бут.` )
  75. store.subscribe( () => sigiCount.value = store.getState().сиги.колличество, sigi.innerHTML += ` ${store.getState().сиги.цена} UAH/пачку`)
  76. store.subscribe( () => chipsCount.value = store.getState().чипсы.колличество, chips.innerHTML += ` ${store.getState().чипсы.цена} UAH/пачку`)
  77. store.subscribe( () => giveMoney.value = store.getState().ЧЕК)
  78. store.subscribe( () => turningIn.value = store.getState().СДАЧА)
  79. countGoods.oninput = () => {
  80. store.dispatch({...createAction(), type: 'СУММА ПОКУПКИ'})
  81. }
  82. buy.onclick = () => {
  83. store.dispatch(createAction())
  84. console.log(store.getState())
  85. }