The purpose of this function is to calculate a price (result) based on a given airline rate table (param 1) and a weight (param 2). The array line in the rates array signify: [weight break, rate/kg, breakpoint].
Example of the calculation:
- check if given weight is below the weight break (
wb), apply the minimum rate, which is thewb * rate;
- if not, check if the weight is below the breakpoint (
bp), calculate theweight * rate; - if the weight is higher than the
bp, apply thewbof the next array times the rate of the next array.
Note: the last line in the rates table does not have a bp. That's simply how these tables are provided.
TLDR:
My code works just fine (see below), but I am very new at this and I wonder if there is a better way to write this little algorithm. I spot recursion, but I am not sure how to write a recursive function. Perhaps this can be written in a more concise way? I am asking the question to get better at coding. Thanks!
rates = [
[ 45, 3.8, 88 ],
[ 100, 3.35, 296 ],
[ 300, 3.3, 492 ],
[ 500, 3.25]
];
function calcPrice(arr, weight) {
let price = 0;
for (let i = 0; i < arr.length; i++) {
if (weight <= arr[i][0]) {
price = arr[i][0] * arr[i][1]; break;
} else if (weight <= arr[i][2] && arr[i][2] !== undefined) {
price = weight * arr[i][1]; break;
} else {
price = weight * arr[i][1];
}
}
return price;
}
console.log(calcPrice(rates, 89);