typestar

inventory.ts in TypeScript

A complete inventory script: typed records in, grouped and totaled report out.

interface Item {
  name: string;
  quantity: number;
  unitPrice: number;
}

const inventory: Item[] = [
  { name: "widget", quantity: 12, unitPrice: 2.5 },
  { name: "gadget", quantity: 3, unitPrice: 19.99 },
  { name: "doohickey", quantity: 40, unitPrice: 0.75 },
];

function totalValue(items: Item[]): number {
  return items.reduce((sum, i) => sum + i.quantity * i.unitPrice, 0);
}

function lowStock(items: Item[], threshold = 5): Item[] {
  return items.filter((i) => i.quantity < threshold);
}

console.log(`total value: $${totalValue(inventory).toFixed(2)}`);
for (const item of lowStock(inventory)) {
  console.log(`low stock: ${item.name} (${item.quantity} left)`);
}

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
660
Tokens
194
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 106 seconds.

Type this snippet

Step 1 of 1 in Encore, step 20 of 20 in Generics.

← Previous