index.html 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>A-Level</title>
  8. </head>
  9. <body>
  10. <div id="assortment"></div>
  11. <select id="fruits">
  12. <option value="apples">apples</option>
  13. <option value="oranges">oranges</option>
  14. <option value="bananas">bananas</option>
  15. </select>
  16. <input type="number" id="quantity" placeholder="quantity of goods">
  17. <input type="number" id="cash" placeholder="give me your cash">
  18. <button id="btn">Buy</button>
  19. <script>
  20. function fruitBuyer(state, {type, whatFruits, howMany, cash}){
  21. if (!state){
  22. return {
  23. apples: {
  24. quantity: 100,
  25. price: 15
  26. },
  27. oranges: {
  28. quantity: 100,
  29. price: 25
  30. },
  31. bananas:{
  32. quantity: 100,
  33. price: 20
  34. },
  35. cashBox: 0
  36. }
  37. }
  38. if (type === 'buy'){
  39. return {
  40. ...state,
  41. [whatFruits]: {
  42. quantity: ((state[whatFruits].quantity - howMany) < 0 || cash < state[whatFruits].price ) ? state[whatFruits].quantity : state[whatFruits].quantity - howMany,
  43. price: state[whatFruits].price
  44. },
  45. cashBox: ((state[whatFruits].quantity - howMany) < 0 || cash < state[whatFruits].price ) ? state.cashBox : (cash * howMany) + state.cashBox
  46. }
  47. }
  48. return state
  49. }
  50. function createStore(reducer){
  51. let state = reducer(undefined, {})
  52. let cbs = []
  53. const getState = () => state
  54. const subscribe = cb => (cbs.push(cb),
  55. () => cbs = cbs.filter(c => c !== cb))
  56. const dispatch = action => {
  57. const newState = reducer(state, action)
  58. if (newState !== state){
  59. state = newState
  60. for (let cb of cbs) cb()
  61. }
  62. }
  63. return {
  64. getState,
  65. dispatch,
  66. subscribe
  67. }
  68. }
  69. const store = createStore(fruitBuyer);
  70. store.subscribe(() => assortment.innerHTML = JSON.stringify(store.getState()));
  71. const buyFruits = (whatFruits, howMany, cash) => ({type: 'buy', whatFruits:`${whatFruits}`, howMany, cash});
  72. btn.addEventListener('click', () =>{
  73. const whatFruits = fruits.value;
  74. const howMany = quantity.value;
  75. const cashValue = cash.value
  76. store.dispatch(buyFruits(whatFruits, howMany, cashValue))
  77. })
  78. store.dispatch(buyFruits('apples',0, 0));
  79. </script>
  80. </body>
  81. </html>