Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - improving on a nested if-else

I have a horrible nested if. There could in the future be even more lines.

if (people < 10) {
    price = 500;
} else if (people >= 10 && people < 25) {
    price = 350;
} else if (people >= 25 && people < 100) {
    price = 250;
} else if (people >= 100) {
    price = 200;
}

The price goes down as the volume goes up. How do I refactor this to make it more maintainable/readable?

Edit: I tried a switch and it was not any better?

like image 595
AlexanderDavidson Avatar asked Nov 08 '18 10:11

AlexanderDavidson


1 Answers

One option would be to use an array that defines the thresholds, then .find the appropriate value in the array. This will be very concise, especially when there are lots of thresholds:

const thresholds = [
  [100, 200], // need 100+ people for the price to be 200
  [25, 250], // else need 25+ people for the price to be 250
  [10, 350],
  [0, 500]
];
function findPrice(people) {
  return thresholds.find(([limit]) => people >= limit)[1];
}

console.log(findPrice(53)); // 53 people
console.log(findPrice(25));
console.log(findPrice(24));
like image 66
CertainPerformance Avatar answered Oct 17 '22 14:10

CertainPerformance