我有这个方法,它接受一个数组并返回所有这些项的数组。此方法计算订购某些物品时获得的赠品数量。它可以工作,但是看起来有很多重复的代码。我想知道,如何最好地重构它?
calculateFreebies(orders) {
const freeItemAmount = [];
const totalAmount = [];
for (const order of orders) {
const items = Math.floor(order.cash / order.price);
const freebies = Math.floor(items / order.bonus_ratio);
if (order.type === 'foo') {
const bar = 0;
const boo = 0;
let foo = 0;
foo = (foo + 1) * freebies;
freeItemAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
totalAmount.push({'\"foo\"': foo + items, '\"bar\"': bar, '\"boo\"' : boo});
} else if (order.type === 'bar') {
const foo = 0;
const boo = 0;
let bar = 0;
bar = (bar + 2) * freebies;
freeItemAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
totalAmount.push({'\"foo\"': foo, '\"bar\"': bar + items, '\"boo\"' : boo});
} else if (order.type === 'boo') {
const bar = 0;
let foo = 0;
let boo = 0;
foo = (foo + 1) * freebies;
boo = (boo + 1) * freebies;
freeItemAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
totalAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo + items});
}
}
return totalAmount;
}
答案 0 :(得分:0)
创建用于计算foo和boo变量的私有函数。例如:
let foo = 0;
let boo = 0;
foo = (foo + 1) * freebies;
boo = (boo + 1) * freebies;
替换为
let foo = calculatePrice(freebies);
let boo = calculatePrice(freebies);
并创建对象(JSON)...
freeItemAmount.push(createItem(foo, bar, boo));
如果bar和boo始终相同,则将其放在常量中(在Mayus中)
freeItemAmount.push(createItem(foo, CONSTANT_BAR, CONSTANT_BOO));
等...
通常,当您阅读不是您自己的代码时,通常不需要了解所有Buniess技术(代码)。您只需要了解Buniess逻辑即可。例如:
for (const order of orders) {
if (isFooProduct(order)) {
freeItemAmount.put(createItem(...));
totalAmount.put(createItem(...));
else if (isBarProduct(order)) {
....
}
.....
}
答案 1 :(得分:0)
首先只声明一次变量,而不是针对每种订单类型声明一次。
然后,对于所有三种订单类型,对freeItemAmount数组的推送均相同。这意味着您可以在if语句之后推送到数组。
最后,如果将项目直接添加到变量中,则可以通过推送到totalAmount数组来进行相同操作。
for (const order of orders) {
const items = Math.floor(order.cash / order.price);
const freebies = Math.floor(items / order.bonus_ratio);
let bar = 0;
let boo = 0;
let foo = 0;
if (order.type === 'foo') {
foo = ((foo + 1) * freebies) + items;
} else if (order.type === 'bar') {
bar = ((bar + 2) * freebies) + items;
} else if (order.type === 'boo') {
foo = (foo + 1) * freebies;
boo = ((boo + 1) * freebies) + items;
}
freeItemAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
totalAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
}