How can I say to JS to increase a value everytime multiple conditions are met..without hardcoding it

Issue

I am trying to figure out this problem, basically my problem is: if the length (in seconds) is < 180 return 500(pences) . For every extra 60 seconds add 70 pences. So if for example I have 240seconds I should return 570pences if I have 300seconds i should return 640pences and so on. How can I achieve this result with JavaScript?

this is my code so far:

    function calculateTaxiFare(seconds) {
        if (seconds < 180) {
   return 500
      // I need something like this without hardcoding
}else if (seconds > 180 && seconds < 240) {
          return 575
}else if ( seconds > 240 && seconds < 300 ) {
          return 640
}
    }

console.log(calculateTaxiFare(245));

Thank you for your support.

Solution

You need to integer divide the (length of time – 180 seconds) by 60 and round upwards to the nearest integer (you can use Math.ceil for that operation) and then multiply that by 70 to get the additional fare, which is then added to the base fare (500):

function calculateTaxiFare(seconds) {
  return 500 + Math.ceil((seconds - 180) / 60) * 70
}

console.log(calculateTaxiFare(245));

Answered By – Nick

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published