|
@@ -0,0 +1,69 @@
|
|
|
+function shoppingCartReducer(state, {type, what, howMach, money}) {
|
|
|
+ if(!state) {
|
|
|
+ return {
|
|
|
+ videoCards: {
|
|
|
+ amount: 100,
|
|
|
+ price: 180
|
|
|
+ },
|
|
|
+ processors: {
|
|
|
+ amount: 100,
|
|
|
+ price: 120
|
|
|
+ },
|
|
|
+ memory: {
|
|
|
+ amount: 100,
|
|
|
+ price: 80
|
|
|
+ },
|
|
|
+ totalMoney: 0
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if(type === 'buy') {
|
|
|
+ return {
|
|
|
+ ...state,
|
|
|
+ [what]: {
|
|
|
+ amount: (state[what].amount - howMach < 0 || money < state[what].price) ? state[what].amount : state[what].amount - howMach,
|
|
|
+ price: state[what].price
|
|
|
+ },
|
|
|
+ totalMoney: (state[what].amount - howMach < 0 || money < state[what].price) ? state.totalMoney : (howMach * money) + state.totalMoney
|
|
|
+ }
|
|
|
+ }
|
|
|
+ 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(shoppingCartReducer);
|
|
|
+
|
|
|
+store.subscribe(() => storeBlock.innerText = JSON.stringify(store.getState()));
|
|
|
+
|
|
|
+const buyAction = (what, howMach, money) => ({type: 'buy', what: `${what}`, howMach, money});
|
|
|
+
|
|
|
+store.dispatch(buyAction('videoCards', 0, 0));
|
|
|
+
|
|
|
+buy.addEventListener('click', () => {
|
|
|
+ let what = goods[goods.options.selectedIndex].value;
|
|
|
+ let howMach = amount.value;
|
|
|
+ let moneyVal = money.value;
|
|
|
+ store.dispatch(buyAction(what, howMach, moneyVal));
|
|
|
+})
|
|
|
+
|