Back to js-conditionals
10-tip-calculator.js
JavaScript
1/**
2 * 🍽️ TipEasy - Restaurant Tip Calculator
3 *
4 * You're building TipEasy, an app that helps diners calculate the right
5 * tip based on how they'd rate their dining experience. No more awkward
6 * mental math at the table!
7 *
8 * Service Rating → Tip Percentage:
9 * - 1 (terrible) → 5%
10 * - 2 (poor) → 10%
11 * - 3 (okay) → 15%
12 * - 4 (good) → 20%
13 * - 5 (excellent) → 25%
14 *
15 * Return an object with:
16 * - tipPercentage: the percentage as a number (e.g., 15)
17 * - tipAmount: the calculated tip rounded to 2 decimal places
18 * - totalAmount: bill + tip rounded to 2 decimal places
19 *
20 * Rules:
21 * - If billAmount is 0 or negative, return null
22 * - If serviceRating is not an integer from 1 to 5, return null
23 *
24 * Example:
25 * calculateTip(50, 4)
26 * → { tipPercentage: 20, tipAmount: 10.00, totalAmount: 60.00 }
27 *
28 * @param {number} billAmount - The bill amount in dollars
29 * @param {number} serviceRating - Service rating from 1 to 5
30 * @returns {{ tipPercentage: number, tipAmount: number, totalAmount: number } | null}
31 */
32export function calculateTip(billAmount, serviceRating) {
33 if(billAmount <= 0){
34 return null
35 }
36
37 if (!Number.isInteger(serviceRating) || serviceRating < 1 || serviceRating > 5) {
38 return null;
39 }
40
41 function getTipPercentage(serviceRating){
42 switch(serviceRating){
43 case 1:
44 return 5;
45 case 2:
46 return 10;
47 case 3:
48 return 15;
49 case 4:
50 return 20;
51 default:
52 return 25;
53 }
54 }
55
56 function getTipAmount(tipPercentage, billAmount){
57 return Number(((tipPercentage/100)*billAmount).toFixed(2))
58 }
59
60 let tipPercentage = getTipPercentage(serviceRating)
61 let tipAmount = getTipAmount(tipPercentage, billAmount)
62 let totalAmount = Number((tipAmount + billAmount).toFixed(2))
63
64 return {tipPercentage, tipAmount, totalAmount}
65
66}
67