Ber*_*dao 1 javascript functional-programming ecmascript-6
这是函数的返回值,我想在数组中应用40%的折扣,以防万一产品颜色为红色。这是回报,正在发挥作用。我想知道一种重构它的方法,也想知道在这种情况下是否可以链接过滤器函数,如果可能的话应该怎么做?另外,如果您可以使用更好的纯函数来做到这一点,我将学习函数式编程。
return cart.map( (x) => {
if (x.color === "red") {
x.price = x.price * 0.4;
}
return x;
});
Run Code Online (Sandbox Code Playgroud)
谢谢
通常,当前代码是可以的,如果您想减少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))
Run Code Online (Sandbox Code Playgroud)