How to do it...

Build a small JavaScript application that will increase or decreased a counter based on the action provided.

  1. Create a new file named counter.js
  2. Define action-types as constants:
      const INCREMENT_COUNTER = 'INCREMENT_COUNTER' 
      const DECREMENT_COUNTER = 'DECREMENT_COUNTER' 
  1. Define two action creators for generating two kinds of actions to increment and decrement the counter:
      const increment = (by) => ({ 
          type: INCREMENT_COUNTER, 
          by, 
      }) 
      const decrement = (by) => ({ 
          type: DECREMENT_COUNTER, 
          by, 
      }) 
  1. Initialize the initial accumulator to 0, then reduce it by passing several actions. The reducer function will decide which kind of action to perform based on the action type:
      const reduced = [ 
          increment(10), 
          decrement(5), 
          increment(3), 
      ].reduce((accumulator, action) => { 
          switch (action.type) { 
              case INCREMENT_COUNTER: 
            return accumulator + action.by 
              case DECREMENT_COUNTER: 
                  return accumulator - action.by 
              default: 
                  return accumulator 
          } 
      }, 0) 
  1. Log the resulting value:
      console.log(reduced) 
  1. Save the file
  2. Open a terminal and run:
       node counter.js
  
  1. Outputs: 8
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.248.13