Skip to the content

Project: clean up this program

JavaScript · Unit 19: Clean code

This program charges the day's sale with a 10% tip. It works, and that's all: it's called f, its data is called a and x, and it only holds exactly two sales.

You're going to rebuild it in pieces, with names and one function per job. The tests tell you if you broke it.

function f(a) {
  const x = a[0] + a[1];
  return x + x / 10;
}
console.log(f([120, 80]));

Prints

220

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    total(sales) adds up every sale, and returns 0 if there were none. Fill in the guard.

  2. 2. Write the code

    Write withTip(sales): the day's total plus a 10% tip, and 0 if there were no sales. Use total, which is already clean, instead of adding things up again. You only touch the body of withTip.

  3. 3. Write the code

    Write perPerson(sales, people): each person's share of the bill with the tip, and 0 if people is 0. Use withTip and start with a guard. You only touch the body of perPerson.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →