'Develop a decreasing price function by step
I'm trying to configure my price list. The price unit must decrease depending the quantity you buy but should keep growing.
I was able to do it in excel, but now I would like to do a function in javascript.
my pricelist in the DB is like this:
min max price
1 9 50
10 19 45
20 29 40
30 49 35
50 79 30
80 90 25
The function depending the price is
qty price function
1-9 qty*50
10-19 (qty-9)*45+(9*50)
20-29 (qty-19)*40+(19*45)
...
80-90 (qty-79)*25+(79*30)
I would like to create a ES6 function that receive the quantity in parameter and return the total price.
UPDATE I was able to create the function but I'm pretty sure that we can improve it.
let priceList= [
{"_id":1,"min":1,"max":9,"price":50},
{"_id":2,"min":10,"max":19,"price":45},
{"_id":3,"min":20,"max":29,"price":40},
{"_id":4,"min":30,"max":49,"price":35},
{"_id":5,"min":50,"max":79,"price":30},
{"_id":6,"min":80,"max":90,"price":25}
]
function sum(qty){
let sum = 0;
let prices = priceList.filter((x)=>x.min<=qty);
var price;
var priceArr=[];
const pricesLength = prices.length;
for (let i = 0; i < pricesLength ; i++) {
price = prices[i];
if(i==0){
priceArr.push(price.price * ((price.max < qty) ? price.max : qty));
} else {
priceArr.push(price.price * ((price.max <= qty) ? price.max - price.min + 1 : qty - price.min + 1) + priceArr[i-1]);
}
}
return priceArr[pricesLength-1];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|