Sikau

JavaScript · Day 29 · about 30 min

Project: Bill splitter

Tips and shares, built from small functions.

Dinner with friends

After a big thakali dinner, everyone asks the same question: "How much do I owe?" Let's build a bill splitter out of small functions, each doing one job.

Small functions, big program

Good programs are built from small, clearly-named pieces. Each piece is easy to test on its own.

const addTip = (bill, percent) => bill + bill * percent / 100;
const share = (amount, people) => amount / people;

const withTip = addTip(2000, 10);
console.log(withTip);
console.log(share(withTip, 4));

Math.round(x) rounds to the nearest whole number — handy for money: Math.round(562.5) is 563.

The rest of this lesson

  • Breaking the problem downexplain
  • Testing each pieceexplain
  • Tip, then sharepredict
  • Order the workorder
  • Step 1: the pieceswrite code
  • Step 2: the splitterchallenge
  • Badge quizquiz
  • Unit 5 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript