← Back to reading
Lab

Tracing a small program

Report a problem in this lab

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.

F-TRACE-V4-1easy · review

Check the first fee row

The pricing support note includes a worksheet for an order with base 1200 and one fee of 75 minor units. Its final quote is plausible, but the helper row needs review.

What needs to change

Correct the first add invocation at P. Record its subtotal and the next operation before approving the worksheet.

Reproduce

  1. In main.ts, use input 1200 75. Locate P in the first add invocation.

Acceptance criteria

  • Helper local
  • Next operation

Notes

Node stdin supplies base 1200 followed by one fee 75. Input parsing and group construction are supplied.

P is immediately before console.log in add. Record the local and the next source operation.

TypeScript number arithmetic is exact for these supplied small integer inputs.

Read only

Sign in with access to this level to check your decisions. You can still inspect the supplied evidence.

Sign in →
main.ts
import { readFileSync } from "node:fs";

function add(base: number, amount: number): number {
  const subtotal = base + amount;

  // Checkpoint P: immediately before this output operation.
  console.log("add", subtotal);

  return subtotal;
}

type FeeGroup = {
  fee: number;
  remaining: number;
  inner: FeeGroup | null;
};

function quote(base: number, group: FeeGroup | null): number {
  const remaining = group?.remaining ?? 0;
  console.log("enter", base, remaining);
  if (group === null) return base;

  const child = quote(add(base, group.fee), group.inner);

  // Checkpoint Q: immediately before this output operation.
  console.log("resume", base, child);

  return child;
}

function main() {
  const [base, ...fees] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);
  let group: FeeGroup | null = null;
  for (let i = fees.length - 1; i >= 0; i--) {
    group = { fee: fees[i], remaining: fees.length - i, inner: group };
  }

  let total = base;
  console.log("start", total);

  total = quote(base, group);

  console.log("done", total);
}

main();
Native command
npx tsc main.ts --noEmit --skipLibCheck --target es2022 --module nodenext --types node && node main.ts
Not checked