rentalCarCost.js (8kyu 36)

Codewars 알고리즘 풀이


Description

  • You will need a rental car in order for you to get around in your vacation.
    • 휴가를 즐기기 위해 렌터카가 필요하다.
  • The manager of the car rental makes you some good offers.
    • 렌터카 관리자가 좋은 제안을 한다.
  • Every day you rent the car costs $40.
    • 렌터카 하루 비용은 $40이다.
  • If you rent the car for 7 or more days, you get $50 off your total.
    • 7일 이상 렌트하면 총 $50이 할인된다.
  • Alternatively, if you rent the car for 3 or more days, you get $20 off your total.
    • 또는 3일 이상 렌트하면 총 $20이 할인된다.
  • Write a code that gives out the total amount for different days.
    • 렌트 일수에 따라 total amount를 반환한다.



Solution 01

function rentalCarCost(days) {
  if (days < 3) return days * 40;
  if (days >= 3 && days < 7) return days * 40 - 20;
  if (days >= 7) return days * 40 - 50;
}

rentalCarCost(1);   // 40 (40 * 1)
rentalCarCost(2);   // 80 (40 * 2)
rentalCarCost(3);   // 100 (40 * 3 - 20)
rentalCarCost(4);   // 140 (40 * 4 - 20)
rentalCarCost(5);   // 180 (40 * 5 - 20)
rentalCarCost(6);   // 220 (40 * 6 - 20)
rentalCarCost(7);   // 230 (40 * 7 - 50)
rentalCarCost(8);   // 270 (40 * 8 - 50)
rentalCarCost(9);   // 310 (40 * 9 - 50)
rentalCarCost(10);  // 350 (40 * 10 - 50)


Solution 02

function rentalCarCost(days) {
  if (days >= 7) return days * 40 - 50;
  else if (days >= 3) return days * 40 - 20;
  else return days * 40;
}

rentalCarCost(1);   // 40 (40 * 1)
rentalCarCost(2);   // 80 (40 * 2)
rentalCarCost(3);   // 100 (40 * 3 - 20)
rentalCarCost(4);   // 140 (40 * 4 - 20)
rentalCarCost(5);   // 180 (40 * 5 - 20)
rentalCarCost(6);   // 220 (40 * 6 - 20)
rentalCarCost(7);   // 230 (40 * 7 - 50)
rentalCarCost(8);   // 270 (40 * 8 - 50)
rentalCarCost(9);   // 310 (40 * 9 - 50)
rentalCarCost(10);  // 350 (40 * 10 - 50)


Solution 03

function rentalCarCost(days) {
  return days * 40 - (days >= 7 ? 50 : days >= 3 ? 20 : 0);
}

rentalCarCost(1);   // 40 (40 * 1)
rentalCarCost(2);   // 80 (40 * 2)
rentalCarCost(3);   // 100 (40 * 3 - 20)
rentalCarCost(4);   // 140 (40 * 4 - 20)
rentalCarCost(5);   // 180 (40 * 5 - 20)
rentalCarCost(6);   // 220 (40 * 6 - 20)
rentalCarCost(7);   // 230 (40 * 7 - 50)
rentalCarCost(8);   // 270 (40 * 8 - 50)
rentalCarCost(9);   // 310 (40 * 9 - 50)
rentalCarCost(10);  // 350 (40 * 10 - 50)


Solution 04

function rentalCarCost(days) {
  const dayCost = 40;
  let discount = 0;
  
  if (days >= 3) discount += 20;
  if (days >= 7) discount += 30;
  
  return days * dayCost - discount;
}

rentalCarCost(1);   // 40 (40 * 1)
rentalCarCost(2);   // 80 (40 * 2)
rentalCarCost(3);   // 100 (40 * 3 - 20)
rentalCarCost(4);   // 140 (40 * 4 - 20)
rentalCarCost(5);   // 180 (40 * 5 - 20)
rentalCarCost(6);   // 220 (40 * 6 - 20)
rentalCarCost(7);   // 230 (40 * 7 - 50)
rentalCarCost(8);   // 270 (40 * 8 - 50)
rentalCarCost(9);   // 310 (40 * 9 - 50)
rentalCarCost(10);  // 350 (40 * 10 - 50)