CodeBlanks Logo Icon CodeBlanks

Total calculation

Learn to calculate the cart total.

Cart total

The total of a cart is the sum of product.price * quantity for every CartItem. You can compute it in a single pass with reduce. The initial value should be 0.

function total(cart: Cart): number {
  return cart.items.reduce((sum, i) => sum + i.product.price * i.quantity, 0);
}

How reduce works

reduce collapses an array into a single value. The first parameter takes an accumulator and an item; the second is the initial value. Here we start at 0 and add each item's price to the accumulator.

const sum = cart.items.reduce((acc, i) => acc + i.product.price * i.quantity, 0);
// acc: previous sum, i: CartItem, 0: initial value

Practice Write the total function

Define Product, CartItem, Cart interfaces. Write a function total(cart: Cart): number. For each item compute i.product.price * i.quantity and sum them all with reduce. The initial value should be 0. Test with a cart of two items and print the result.

Starter code

index.ts
// Product, CartItem, Cart arayüzlerini tanımla
// total(cart: Cart): number yaz
// her öğenin fiyatını miktarıyla çarp ve topla
// iki öğeli bir sepetle test et, sonucu yazdır

Sample solution

index.ts
interface Product { id: string; name: string; price: number; }
interface CartItem { product: Product; quantity: number; }
interface Cart { items: CartItem[]; }

function total(cart: Cart): number {
  return cart.items.reduce((sum, i) => sum + i.product.price * i.quantity, 0);
}

const cart: Cart = {
  items: [
    { product: { id: "a", name: "Elma", price: 5 }, quantity: 2 },
    { product: { id: "b", name: "Armut", price: 3 }, quantity: 4 }
  ]
};
console.log(total(cart));

Expected output

22

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is the total price of a CartItem computed?

  • product.price * quantity Correct answer
  • product.price + quantity
  • product.price
  • quantity

Explanation: The total price of an item is the product price times the quantity: product.price * quantity. Addition would be wrong.

2 Complete the multiplication operator

Question
const itemTotal = i.product.price ____ i.quantity;
Answer
const itemTotal = i.product.price * i.quantity;

Explanation: The item total is price times quantity: i.product.price * i.quantity. +, /, and - perform the wrong operation.

3 Total computation parts

Term Meaning
price * quantity Item total price
reduce((sum, i) => ..., 0) Sum all items
0 Initial value
sum + itemTotal Accumulator update

All lessons in Beginner