0

I can't implement the function tipPercentage that takes the argument rating as a string and return the values:

  1. terrible or poor, then returns 3
  2. good or great, then returns 10
  3. excellent, returns 20
  4. none of the above, returns 0

the input format for custom testing must be that the first line contains a integer, n, denoting the value of rating

HELP FOR A BEGGINNER!!!

StudioTime
  • 22,603
  • 38
  • 120
  • 207

3 Answers3

1

You can use a switch statement to do this relatively easily, we check the input rating, then return the relevant tip percentage.

If we don't have a tip percentage for the rating, we'll fall back to the default condition, and return 0.

One could also use a map, though a switch statement is probably more flexible.

// Takes rating as a string and return the tip percentage as an integer.
function tipPercentage(rating) {
    switch ((rating + "").toLowerCase()) {
        case "terrible":
        case "poor":    
            return 3;

        case "good":
        case "great": 
            return 10;

        case "excellent":
            return 20;

        default:
            return 0;
    }
}

let ratings = ["excellent", "good", "great", "poor", "terrible", "meh", null];
for(let rating of ratings) {
    console.log(`tipPercentage(${rating}):`, tipPercentage(rating))
}
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0
function tipPercentage(rating) {
  switch(rating) {
  case "terrible":
  case "poor": 
    return 3; break;
  case "good":
  case "great":
    return 10; break;
  case "excellent":
    return 20; break;
  default:
    return 0;
  }
}

edddd
  • 433
  • 3
  • 17
0

Instead of a switch statement you could simply use an object:

const tipPercentage = {
  'excellent': 20,
  'good': 10,
  'great': 10,
  'terrible': 3,
  'poor': 3,
}

const myRatings = [
    "excellent",
    "good",
    "great",
    "terrible",
    "whatever",
    undefined
];

for (let rating of myRatings) {
  // Tip percentage, or 0 if it doesn't exist
  console.log(rating, tipPercentage[rating] || 0)
}
StudioTime
  • 22,603
  • 38
  • 120
  • 207