redux.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. function shoppingCartReducer(state, {type, what, howMach, money}) {
  2. if(!state) {
  3. return {
  4. videoCards: {
  5. amount: 100,
  6. price: 180
  7. },
  8. processors: {
  9. amount: 100,
  10. price: 120
  11. },
  12. memory: {
  13. amount: 100,
  14. price: 80
  15. },
  16. totalMoney: 0
  17. }
  18. }
  19. if(type === 'buy') {
  20. return {
  21. ...state,
  22. [what]: {
  23. amount: (state[what].amount - howMach < 0 || money < state[what].price) ? state[what].amount : state[what].amount - howMach,
  24. price: state[what].price
  25. },
  26. totalMoney: (state[what].amount - howMach < 0 || money < state[what].price) ? state.totalMoney : (howMach * money) + state.totalMoney
  27. }
  28. }
  29. return state;
  30. }
  31. function createStore(reducer){
  32. let state = reducer(undefined, {});
  33. let cbs = [];
  34. const getState = () => state;
  35. const subscribe = cb => (cbs.push(cb),
  36. () => cbs = cbs.filter(c => c !== cb));
  37. const dispatch = action => {
  38. const newState = reducer(state, action);
  39. if (newState !== state){
  40. state = newState;
  41. for (let cb of cbs) cb();
  42. }
  43. }
  44. return {
  45. getState,
  46. dispatch,
  47. subscribe
  48. }
  49. }
  50. const store = createStore(shoppingCartReducer);
  51. store.subscribe(() => storeBlock.innerText = JSON.stringify(store.getState()));
  52. const buyAction = (what, howMach, money) => ({type: 'buy', what: `${what}`, howMach, money});
  53. store.dispatch(buyAction('videoCards', 0, 0));
  54. buy.addEventListener('click', () => {
  55. let what = goods[goods.options.selectedIndex].value;
  56. let howMach = amount.value;
  57. let moneyVal = money.value;
  58. store.dispatch(buyAction(what, howMach, moneyVal));
  59. })