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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With