I created a tip calculator using if-else statements as below:
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);
The calculator returns two arrays: one with the sum of tips and one with the total amount spent (bill + tip).
A friend of mine suggested me, to learn functional programming, to work with map and reduce to create the same application.
At the moment the code below returns an array of 3 NaN: could you please help me completing it and understanding it? Thank you so much.
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"))