Problem overview
The cart now holds several items, stored in three parallel arrays: items (names), prices (price of one unit) and quantities (how many of each). The item at position 0 is a Shirt that costs 25 and was bought twice, the item at position 1 is Pants, and so on. The program must print one receipt line per item in the form Name xQ: $subtotal, then a final Total line, all joined by newlines into a string result that is printed with console.log.
Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195
The earlier versions handled one item and a shipping rule. This one repeats the same work for every item, so a loop is the natural tool.
Approach: one pass with a running total
Three arrays that line up by position are called parallel arrays: index i in each of them describes the same item. A for loop from 0 to items.length - 1 visits every position, and inside it prices[i] * quantities[i] is that item's subtotal.
Two things have to be collected while the loop runs. The first is the list of receipt lines, kept in an array of strings called lines. The second is the running total, a number that starts at 0 and grows by each subtotal. The total line only makes sense once every item has been added, so it is pushed after the loop, not inside it.
Tracing the loop on the starter data gives these values:
| i | item | sub | total after |
|---|---|---|---|
| 0 | Shirt | 50 | 50 |
| 1 | Pants | 40 | 90 |
| 2 | Shoes | 60 | 150 |
| 3 | Hat | 45 | 195 |
Step by step
- Create
linesas an emptystring[]. Declaring it withconstis fine: the array itself is never replaced, only added to. - Create
totalwithletand start it at 0. It changes on every pass, so it can't be aconst. - Write the loop
for (let i = 0; i < items.length; i++), and close its brace immediately. The conditioni < items.lengthstops after the last valid index. - Compute
subinside the loop: the price times the quantity at the same index. - Add
subtototal. - Push the item's row onto
lines: the name, a space andx, the quantity, a colon and space, a dollar sign and the subtotal. The+operator turns the numbers into text. - After the loop, push the Total row. It runs once, so it sits outside the braces.
- Join the rows into
resultwithlines.join("\n"). - Print
result.
The solution in TypeScript
const items: string[] = ["Shirt", "Pants", "Shoes", "Hat"];
const prices: number[] = [25, 40, 60, 15];
const quantities: number[] = [2, 1, 1, 3];
const lines: string[] = [];
let total: number = 0;
for (let i = 0; i < items.length; i++) {
const sub: number = prices[i] * quantities[i];
total = total + sub;
lines.push(items[i] + " x" + quantities[i] + ": $" + sub);
}
lines.push("Total: $" + total);
const result: string = lines.join("\n");
console.log(result);
Details that matter in TypeScript:
joinputs its separator only between elements. The result has no newline after the last row, which is what the output needs. Building the string withresult += row + "\n"would leave a trailing newline.- Array indexing is not checked at run time. If
priceswere shorter thanitems,prices[i]would beundefined, andundefined * 2isNaN. The loop would not stop with an error. The three arrays have to stay the same length. - The annotations, such as
string[]andnumber, are erased when the code is compiled. They document the code and let the compiler flag mistakes, but they do not convert anything. - The same job could use
for...oforforEach, but both give the item rather than its position, and this lesson needs the position to reach all three arrays. A plain indexed loop is the right fit.
Complexity
The loop runs once per item and does a constant amount of work each time, so the time is O(n) for n items. join also touches each row once. The extra space is O(n) for the lines array.
Edge cases and common mistakes
- Putting the Total push inside the loop. The receipt would then have a Total row after every item.
- Forgetting to reset
total. It must start at 0 before the loop, not inside it, or each pass would throw away the earlier sum. - Using
<=in the loop condition. Index 4 doesn't exist, soitems[4]isundefined. The extra row readsundefined xundefined: $NaN, and the Total line becomesTotal: $NaNtoo, because oneNaNpoisons every sum it joins. - An empty cart. With three empty arrays the loop body never runs and the output is just
Total: $0. - Decimal prices. Doubles can't store most decimals exactly. With prices
[19.99, 5.1, 60, 0.1]and quantities[3, 3, 1, 3], the Pants row prints$15.299999999999999and the Hat row$0.30000000000000004. Round for display, for example withtoFixed(2), or keep amounts in cents. The lesson's whole-number prices stay exact.
Testing
Change the arrays in the editor above and compare with these results, produced by the reference solution:
- Three empty arrays print
Total: $0. - One item,
["Hat"]with price[15]and quantity[3], prints aHat x3: $45row and thenTotal: $45. The total always equals the sum of the rows above it.
