这是函数中的返回值,我想在数组中应用 40% 的折扣,以防产品颜色为红色。这是返回,它正在工作。 我想知道一种重构它的方法,我也想知道在这种情况下是否可以链接过滤器功能,如果可能的话应该怎么做? 另外,如果您可以使用更好的纯函数来做到这一点,我将不胜感激,我正在学习函数式编程。
return cart.map( (x) => {
if (x.color === "red") {
x.price = x.price * 0.4;
}
return x;
});
谢谢
最佳答案
目前的代码大体上还可以,如果你想减少 if 语句的数量并重用 isRed
过滤器和 discount
函数,那么你可以将其更改为类似于:
const cart = [{price: 3, color: 'red'}, {price: 3, color: 'blue'}];
const applyIf = (condition, fn) => {
return x => condition(x) ? fn(x) : x;
}
const isRed = x => x.color === 'red';
const discount = x => ({ ...x, price: x.price * 0.4 });
cart.map(applyIf(isRed, discount))
关于Javascript 重构,可以使用 map 和 filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56934222/