satyacode
Background
Back to js-conditionals

07-coffee-shop.js

JavaScript
1/**
2 * ☕ Bean & Brew Cafe
3 *
4 * Bean & Brew, the cozy neighborhood cafe, wants to go digital! They
5 * need a system that calculates the total price of a coffee order.
6 * Here's their menu:
7 *
8 * Base price by size:
9 *   - "small"  → $3.00
10 *   - "medium" → $4.00
11 *   - "large"  → $5.00
12 *
13 * Add-on for coffee type:
14 *   - "regular"    → +$0.00
15 *   - "latte"      → +$1.00
16 *   - "cappuccino" → +$1.50
17 *   - "mocha"      → +$2.00
18 *
19 * Optional extras:
20 *   - whippedCream → +$0.50 (if true)
21 *   - extraShot    → +$0.75 (if true)
22 *
23 * Rules:
24 *   - If size is not "small", "medium", or "large", return -1
25 *   - If type is not "regular", "latte", "cappuccino", or "mocha", return -1
26 *   - Return the total price rounded to 2 decimal places
27 *
28 * @param {string} size - "small", "medium", or "large"
29 * @param {string} type - "regular", "latte", "cappuccino", or "mocha"
30 * @param {{ whippedCream?: boolean, extraShot?: boolean }} extras - Optional extras
31 * @returns {number} Total price or -1 for invalid input
32 */
33export function calculateCoffeePrice(size, type, extras = {}) {
34  if(!(size == "small" || size == "medium" || size == "large")){
35    return -1
36  }
37
38  if(!(type == "regular" || type == "latte" || type == "cappuccino" || type == "mocha")){
39    return -1
40  }
41
42  let price = 0.00;
43
44  switch(size){
45    case "small":
46      price += 3.00;
47      break;
48    case "medium":
49      price += 4.00;
50      break;
51    default:
52      price += 5.00;    
53  }
54
55  switch(type){
56    case "regular":
57      price += 0.00;
58      break;
59    case "latte":
60      price += 1.00;
61      break
62    case "cappuccino":
63      price += 1.50;  
64      break
65    default:
66      price += 2.00
67  }
68
69  extras.whippedCream? price += 0.50 : price
70  extras.extraShot ? price += 0.75 : price
71
72return price
73}
74