google spreadsheet - Javascript look-up function optimization -
i'm writing custom function google sheet using javascript, should return value based upon table.
i've got works, feels extremely ugly lots of nested if statements. how improved readability?
function price(msrp, order_quantity) { var percentage; if(order_quantity >= 200 && order_quantity <= 400) { if(msrp >=49 && msrp <= 99) { percentage = 0.07; } else if (msrp >=100 && msrp <= 249) { percentage = 0.06; } else if (msrp >=250 && msrp <= 499) { percentage = 0.05; } else if (msrp >=500) { percentage = 0.04; } else { return null; } } else if (order_quantity >= 500 && order_quantity <= 900) { if(msrp >=49 && msrp <= 99) { percentage = 0.06; } else if (msrp >=100 && msrp <= 249) { percentage = 0.05; } else if (msrp >=250 && msrp <= 499) { percentage = 0.04; } else if (msrp >=500) { percentage = 0.03; } else { return null; } } else if (order_quantity >= 1000 && order_quantity <= 1400) { if(msrp >=49 && msrp <= 99) { percentage = 0.07; } else if (msrp >=100 && msrp <= 249) { percentage = 0.06; } else if (msrp >=250 && msrp <= 499) { percentage = 0.05; } else if (msrp >=500) { percentage = 0.04; } else { return null; } } else if (order_quantity >= 1500) { if(msrp >=49 && msrp <= 99) { percentage = 0.04; } else if (msrp >=100 && msrp <= 249) { percentage = 0.03; } else if (msrp >=250 && msrp <= 499) { percentage = 0.025; } else if (msrp >=500) { percentage = 0.015; } else { return null; } } else { return null; } return msrp * percentage; }
you define of levels in arrays , use instance array.filter:
function price (msrp, order_quantity) { var percentagelevels = [ [0.07, 0.06, 0.05, 0.04], [0.06, 0.05, 0.04, 0.03], [0.04, 0.03, 0.025, 0.015] ], quantitylevels = [ { min: 200, max: 400, percentages: percentagelevels[0] }, { min: 500, max: 900, percentages: percentagelevels[1] }, { min: 1000, max: 1400, percentages: percentagelevels[0] }, { min: 1500, max: number.max_value, percentages: percentagelevels[2] } ], msrplevels = [ { min: 49, max: 99 }, { min: 100, max: 249 }, { min: 250, max: 499 }, { min: 500, max: number.max_value } ], percentages = (quantitylevels.filter(function (q) { return q.min <= order_quantity && order_quantity <= q.max; })[0] || {}).percentages, foundmsrp = percentages ? msrplevels.filter(function (m, i) { msrplevels[i].percentage = percentages[i]; return m.min <= msrp && msrp <= m.max; })[0] : null; if (!percentages || !foundmsrp) { return null; } return msrp * foundmsrp.percentage; };
the call quantitylevels.filter()
find quantitylevel order_quantity falls into, if any, , call msprlevels.filter()
maps percentage value each msprlevel , returns level matches know if foundmspr
has value foundmspr.percentage
has percentage multiplier want.
Comments
Post a Comment