Back to js-conditionals
11-parking-fee.js
JavaScript
1/**
2 * 🅿️ City Central Parking
3 *
4 * City Central Parking garage is the busiest in downtown. They need an
5 * automated system to calculate parking fees. Different vehicle types
6 * have different rates, and there's a daily maximum so customers
7 * aren't overcharged.
8 *
9 * Rates (first hour / each additional hour):
10 * - "car": $5 first hour, then $3/hour
11 * - "motorcycle": $3 first hour, then $2/hour
12 * - "bus": $10 first hour, then $7/hour
13 *
14 * Daily Maximum (fee can never exceed this):
15 * - "car": $30
16 * - "motorcycle": $18
17 * - "bus": $60
18 *
19 * Rules:
20 * - Partial hours are rounded UP (e.g., 1.5 hours → 2 hours)
21 * - The fee should never exceed the daily maximum
22 * - If hours is 0 or negative, return -1
23 * - If vehicleType is not "car", "motorcycle", or "bus", return -1
24 *
25 * Examples:
26 * - car, 1 hour → $5
27 * - car, 3 hours → $5 + $3 + $3 = $11
28 * - car, 0.5 hours → rounds up to 1 hour → $5
29 * - car, 24 hours → $5 + 23×$3 = $74 → capped at $30
30 *
31 * @param {number} hours - Number of hours parked
32 * @param {string} vehicleType - "car", "motorcycle", or "bus"
33 * @returns {number} Parking fee or -1 for invalid input
34 */
35export function calculateParkingFee(hours, vehicleType) {
36 if(!(vehicleType == "car" || vehicleType == "motorcycle" || vehicleType == "bus")){
37 return -1
38 }
39
40 if(hours <= 0){
41 return -1
42 }
43
44 let fee;
45 hours = Math.ceil(hours)
46
47 if(vehicleType == "car" ){
48 hours < 1? fee = 5: fee = (3 * (hours-1)) + 5
49
50 if(fee > 30){
51 return 30
52 }
53 return fee
54 }
55
56 if(vehicleType == "motorcycle" ){
57 hours < 1? fee = 3: fee = (2 * (hours-1)) + 3
58
59 if(fee > 18){
60 return 18
61 }
62
63 return fee
64 }
65
66 if(vehicleType == "bus" ){
67 hours < 1? fee = 10: fee = (7 * (hours-1)) + 10
68
69 if(fee > 60){
70 return 60
71 }
72 return fee
73 }
74
75}
76