Course outline · 0% complete

0/29 lessons0%

Course overview →

Projects: cart calculator and text stats

lesson 9-2 · ~14 min · 29/29

Project A: the cart calculator

Every checkout page runs this exact math. The model is an array of objects again, each with a price and a qty. The rules:

  1. Each line costs price × qty.
  2. The total is the sum of all lines, a perfect job for reduce (lesson 7-3).
  3. Orders over $50 earn a 10% discount, so the customer pays total × 0.9.
  4. Money is displayed with toFixed(2) (lesson 8-2), always at the last step.

Notice how small each piece is. sum + item.price * item.qty is the whole business logic of a checkout line. Projects feel hard until you write the data shape down, then every function becomes a one-liner you already know.

Code exercise · javascript

The full cart calculator. Trace the reduce by hand first: 25 × 2 = 50, then 4.5 × 3 = 13.5, total 63.5. Then run.

Project B: text statistics

Now a tool that reads a sentence and reports on it, the seed of every word counter and search engine tokenizer. The plan uses only tools you own:

  1. split(" ") from lesson 8-1 turns the sentence into an array of words.
  2. Word count is just .length (lesson 4-1).
  3. Counting long words is filter + .length (lesson 7-1).
  4. Finding the longest word is the biggest-so-far loop from lesson 4-3, comparing w.length instead of the values themselves.

That is the entire project. You are about to write it yourself.

Code exercise · javascript

Your turn, the full text stats tool. Print three lines: the word count, how many words have more than 4 letters, and the longest word (the first one wins a tie).

Problem

Trace the cart by hand: [{ price: 10, qty: 2 }, { price: 5, qty: 1 }] run through cartTotal. What number does it return?

Quiz

You finished the course. A friend asks which JavaScript tool replaces Python's f-strings, sum() with a start value, and dict.items(). In order, which trio is right?