gpt4 book ai didi

Javascript:了解应用于小费计算器的 map 和 reduce

转载 作者:行者123 更新时间:2023-11-30 20:07:43 24 4
gpt4 key购买 nike

我使用 if-else 语句创建了一个小费计算器,如下所示:

var billRestaurant1 = 124;
var billRestaurant2 = 48;
var billRestaurant3 = 268;


function myTip (bill) {
if (bill < 50) {
var tip = bill * 20 / 100;
return tip;
} else if (bill > 49 && bill < 200) {
var tip = bill * 15 / 100;
return tip;
} else {
var tip = bill * 10 / 100;
return tip;
}
}

var tipRestaurant1 = myTip(billRestaurant1);
var tipRestaurant2 = myTip(billRestaurant2);
var tipRestaurant3 = myTip(billRestaurant3);

// console.log(tipRestaurant1, tipRestaurant2, tipRestaurant3)
var sumOfTips = [tipRestaurant1, tipRestaurant2, tipRestaurant3]
console.log(sumOfTips);

var sumOfBillsAndTips = [(billRestaurant1 + tipRestaurant1),(billRestaurant2 + tipRestaurant2),(billRestaurant3 + tipRestaurant3)];
console.log(sumOfBillsAndTips);

计算器返回两个数组:一个包含小费总和,一个包含总花费金额(账单 + 小费)。

我的一个 friend 建议我学习函数式编程,使用 map 和 reduce 来创建相同的应用程序。

目前下面的代码返回一个 3 NaN 的数组:你能帮我完成它并理解它吗?非常感谢。

const data = [
{"bill":120, "user_entered_tip": 10},
{"bill":70, "user_entered_tip": 15},
{"bill":25, "user_entered_tip": 20}
];

const get_sum = function(data){
return data.reduce(function(prev, curr){
return prev + curr
},0);
};

const get_bill = function(bill, key){

return bill.map(function(currentValue){
return currentValue + (currentValue * (currentValue[key] / 100));
});
};


console.dir(get_bill(data, "user_entered_tip"))

最佳答案

A friend of mine suggested me, to learn functional programming, to work with map and reduce to create the same application.

是的,我在学习 FP 时也是这样开始的 :) 我对简洁的最高建议是

  1. 将列表(即 array)与 function 分开(仅对 1 个元素进行操作)
  2. 使用 map() 函数将这两者结合起来

考虑以下解决方案-

const data = [
{"bill":120, "tipPercent": 10},
{"bill":70, "tipPercent": 15},
{"bill":25, "tipPercent": 20}
]

const tips = data.map(d => d.bill * d.tipPercent / 100)
const totals = data.map((d, idx) => d.bill + tips[idx])

console.log('TIPS:', tips, ', TOTALS:', totals)

希望对您的学习有所帮助。干杯,

关于Javascript:了解应用于小费计算器的 map 和 reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52706824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com