본문 바로가기

Programming/JavaScript

Coding Challenge #2 - tip calculator with arrays

Tried 👏👏👏

const tips = [125, 555, 44];

const calcTip = function (billValue) {
    if (billValue >= 50 && billValue <= 300) {
        return billValue * 0.15
    } else {
        return billValue * 0.2
    }
}

console.log(calcTip(100));
// prints 15

const bills = [calcTip(tips[0]), calcTip(tips[1]), calcTip(tips[tips.length - 1])];
const total = [tips[0] + bills[0], tips[1] + bills[1], tips[tips.length - 1] + bills[bills.length - 1]];

console.log(bills); // prints [18.75, 111, 8.8]
console.log(total); // prints [143.75, 666, 52.8]

 

Answer

const calcTip = function (bill) {
    return bill >= 50 && bill <= 300 ? bill * 0.15 : bill * 0.2;
}

// Arrow function
// const calcTip = bill => bill >= 50 && billl <= 300 ? bill * 0.15 : bill * 0.2;

const bills = [125, 555, 44];
const tips = [calcTip(bills[0]), calcTip(bills[1]), calcTip(bills[2])];
const totals = [bills[0] + tips[0], bills[1] + tips[1], bills[2] + tips[2]];
console.log(bills, tips, totals); // prints (3) [125, 555, 44] (3) [18.75, 111, 8.8] (3) [143.75, 666, 52.8]

'Programming > JavaScript' 카테고리의 다른 글

Dot vs. Bracket Notation  (0) 2022.09.11
Introduction to Objects  (0) 2022.09.11
Basic Array Operations (Methods)  (0) 2022.09.10
Introduction to Arrays  (0) 2022.09.10
Coding Challenge #1 - who's win?  (0) 2022.09.09