1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>A-Level</title>
- </head>
- <body>
- <div id="assortment"></div>
- <select id="fruits">
- <option value="apples">apples</option>
- <option value="oranges">oranges</option>
- <option value="bananas">bananas</option>
- </select>
- <input type="number" id="quantity" placeholder="quantity of goods">
- <input type="number" id="cash" placeholder="give me your cash">
- <button id="btn">Buy</button>
- <script>
- function fruitBuyer(state, {type, whatFruits, howMany, cash}){
- if (!state){
- return {
-
- apples: {
- quantity: 100,
- price: 15
- },
- oranges: {
- quantity: 100,
- price: 25
- },
- bananas:{
- quantity: 100,
- price: 20
- },
- cashBox: 0
- }
- }
- if (type === 'buy'){
- return {
- ...state,
- [whatFruits]: {
- quantity: ((state[whatFruits].quantity - howMany) < 0 || cash < state[whatFruits].price ) ? state[whatFruits].quantity : state[whatFruits].quantity - howMany,
- price: state[whatFruits].price
- },
- cashBox: ((state[whatFruits].quantity - howMany) < 0 || cash < state[whatFruits].price ) ? state.cashBox : (cash * howMany) + state.cashBox
-
- }
- }
- 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(fruitBuyer);
- store.subscribe(() => assortment.innerHTML = JSON.stringify(store.getState()));
- const buyFruits = (whatFruits, howMany, cash) => ({type: 'buy', whatFruits:`${whatFruits}`, howMany, cash});
- btn.addEventListener('click', () =>{
- const whatFruits = fruits.value;
- const howMany = quantity.value;
- const cashValue = cash.value
- store.dispatch(buyFruits(whatFruits, howMany, cashValue))
- })
- store.dispatch(buyFruits('apples',0, 0));
- </script>
- </body>
- </html>
|