Back to Freecodecamp

Challenge 215: Parking Fee Calculator

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d6.md

latest2.4 KB
Original Source

--description--

Given two strings representing the time you parked your car and the time you picked it up, calculate the parking fee.

  • The given strings will be in the format "HH:MM" using a 24-hour clock. So "14:00" is 2pm for example.
  • The first string will be the time you parked your car, and the second will be the time you picked it up.
  • If the pickup time is earlier than the entry time, it means the parking spanned past midnight into the next day.

Fee rules:

  • Each hour parked costs $3.
  • Partial hours are rounded up to the next full hour.
  • If the parking spans overnight (past midnight), an additional $10 overnight fee is applied.
  • There is a minimum fee of $5 (only used if the total would be less than $5).

Return the total cost in the format "$cost", "$5" for example.

--hints--

calculateParkingFee("09:00", "11:00") should return "$6".

js
assert.equal(calculateParkingFee("09:00", "11:00"), "$6");

calculateParkingFee("10:00", "10:30") should return "$5".

js
assert.equal(calculateParkingFee("10:00", "10:30"), "$5");

calculateParkingFee("08:10", "10:45") should return "$9".

js
assert.equal(calculateParkingFee("08:10", "10:45"), "$9");

calculateParkingFee("14:40", "23:10") should return "$27".

js
assert.equal(calculateParkingFee("14:40", "23:10"), "$27");

calculateParkingFee("18:15", "01:30") should return "$34".

js
assert.equal(calculateParkingFee("18:15", "01:30"), "$34");

calculateParkingFee("11:11", "11:10") should return "$82".

js
assert.equal(calculateParkingFee("11:11", "11:10"), "$82");

--seed--

--seed-contents--

js
function calculateParkingFee(parkTime, pickupTime) {

  return parkTime;
}

--solutions--

js
function calculateParkingFee(parkTime, pickupTime) {
  function toMinutes(time) {
    const [hours, minutes] = time.split(":").map(Number);
    return hours * 60 + minutes;
  }

  const entryMinutes = toMinutes(parkTime);
  const exitMinutes = toMinutes(pickupTime);

  let totalMinutes;
  let overnight = false;

  if (exitMinutes < entryMinutes) {
    overnight = true;
    totalMinutes = (24 * 60 - entryMinutes) + exitMinutes;
  } else {
    totalMinutes = exitMinutes - entryMinutes;
  }

  const hours = Math.ceil(totalMinutes / 60);
  let cost = hours * 3;

  if (overnight) {
    cost += 10;
  }

  if (cost < 5) {
    cost = 5;
  }

  return `$${cost}`;
}