我有一个要求,用户有自己的基数,并会购买更多的计数产品。
我有折扣系统:
var b1 = { min: 1, max: 5, discount: 0.01 }
var b2 = { min: 6, max: 10, discount: 0.02 }
var b3 = { min: 11, max: 15, discount: 0.03 }
var b4 = { min: 16, max: 20, discount: 0.04 }
var b = [b1, b2, b3, b4] // this is the discount system
有一个要求,应该是get_discounts
方法,通过它我可以得到新的购买产品'折扣。
var a = 5 // this is the base count for user own.
console.log(get_discount(a, 7, b)) // the 7 is new buy. I want to get the discounts of the 7
// [
// { count: 2, discount: 0.03 } // 11, 12 ( 11 <= a + 7 <=15 )
// { count: 5, discount: 0.02 } // ( 6 <= a + 7 <=10 )
// ]
// there exclude the `1 -> 5` (exclude the `a` for discount) . the list counts are 2, 5 (2+5 = 7)
我试过了:
function get_discount(a , new_count, b) {
var discounts = []
var tem_count = a + new_count
for(index in b){
var item = b[index]
if (tem_count >= item.min && tem_count <= item.max){
var discount_obj = {
count: tem_count - item.min + 1,
disocunt: item.discount
}
tem_count -= discount_obj.count
return discount_obj
}
}
}
我只得到
{ count: 2, disocunt: 0.03 }
有一个明显的问题,而不是预期的效果。
谁可以帮助优化功能?
答案 0 :(得分:1)
您可以使用Array#reduceRight
。
>>> np.repeat(np.repeat(np.random.randint(0, 256, (4, 4)), 2, 0), 2, 1)
array([[ 41, 41, 29, 29, 103, 103, 67, 67],
[ 41, 41, 29, 29, 103, 103, 67, 67],
[231, 231, 203, 203, 231, 231, 157, 157],
[231, 231, 203, 203, 231, 231, 157, 157],
[ 18, 18, 126, 126, 15, 15, 196, 196],
[ 18, 18, 126, 126, 15, 15, 196, 196],
[198, 198, 152, 152, 74, 74, 211, 211],
[198, 198, 152, 152, 74, 74, 211, 211]])
function getDiscount(offset, amount, table) {
var value = offset + amount;
return table.reduceRight((r, { min, max, discount }) => {
var count = value - min + 1;
if (value > amount && min <= value && value <= max) {
r.push({ count, discount });
value -= count;
}
return r;
}, []);
}
var discounts = [{ min: 1, max: 5, discount: 0.01 }, { min: 6, max: 10, discount: 0.02 }, { min: 11, max: 15, discount: 0.03 }, { min: 16, max: 20, discount: 0.04 }],
oldBuy = 5,
newBuy = 7,
discount = getDiscount(oldBuy, newBuy, discounts);
console.log(discount);
答案 1 :(得分:0)
您可以使用while循环计算新购买次数:
var b1 = { min: 1, max: 5, discount: 0.01 }
var b2 = { min: 6, max: 10, discount: 0.02 }
var b3 = { min: 11, max: 15, discount: 0.03 }
var b4 = { min: 16, max: 20, discount: 0.04 }
var b = [b1, b2, b3, b4]
function get_discount_by_itemcount(tem_count, b) {
for(index in b){
var item = b[index]
if (tem_count >= item.min && tem_count <= item.max){
var discount_obj = {
count: tem_count - item.min + 1,
disocunt: item.discount
}
tem_count -= discount_obj.count
return {
discount_obj: discount_obj,
tem_count: tem_count
}
}
}
}
function get_discount(a , new_count, b) {
var discounts = []
var tem_count = a + new_count
while( tem_count > a){
var obj = get_discount_by_itemcount(tem_count, b)
tem_count = obj.tem_count
discounts.push(obj.discount_obj)
}
return discounts
}
var a = 5
console.log(get_discount(a, 7, b))