repl.it
@ManavMisra/

Fruit Basket

Nodejs

Illustrate switch and `reduce` with an `Object`

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// A fxn. expression uses an ASSIGNMENT OPERATOR
// `min` and `max` are PARAMETERS
// getRandomIntInclusive is a variable name
// `=` is an ASSIGNMENT OPERATOR
const getRandomIntInclusive = (min, max) =>
  Math.floor(Math.random() * (max - min + 1)) + min;

// Generate a Random array with 50 random numbers ranging from 0 to 100.
// const fruitBasket = Array.from({length: 50}, () => getRandomIntInclusive(0, 100));
const fruitBasket = Array.from({length: 50}, () => fruitPicker(1,5));

// FUNCTION DECLARATION
// JS will 'review' or 'read' all function declarations before running the rest of the code. 
function fruitPicker(min, max) {
  const randomNum = getRandomIntInclusive(min, max);

  switch(randomNum) {
    case 1:
      return 'apple';
    case 2:
      return 'banana';
    case 3:
      return 'papaya';
    case 4:
      return 'cherries';
    default:
      return 'mangoes';
  }
}

// `reduce()` takes 2 args: 1 is a CB Fxn. and the other is the initial EMPTY object
const fruitCount = fruitBasket.reduce((totals, currentFruit) => {
  // Check to see if the fruit exists as a key inside of totals.
  // If the fruit already exists as a key in the totals Object, just update the value!!!
  if (currentFruit in totals) {
    // The currentFruit is already listed in `totals` Object, so DO NOT create a duplicate!
    // Instead, just add 1 to it's value
    totals[currentFruit] += 1;
    console.info(totals);
  } else {
    totals[currentFruit] = 1;
    console.info(totals);
  }
  return totals;
}, {})

console.log(fruitCount);
?