d4-refactor-orders--x-ai-grok-4-7

The attached module computes order totals and works, but it is exactly the kind of code AI assistants produce: redundant machinery, type laundering, narration comments, a needless wrapper layer. Rewrite it as a clean TypeScript module of the same public behavior (computeTotal, applyDiscount, summarize are called by other code and their signatures must keep accepting the same inputs). Do not change observable behavior. Add focused tests for the discount and rounding edges. Accompany the code with a brief explanation of what you changed and why.

ModelGrok 4.7 (xAI) x-ai/grok-4.7
Taskd4-refactor-orders · refactor · typescript · tests expected
Harnessopenrouter-chat-completions openrouter-chat-2026-09-22 at temperature 0.3
Generated2026-09-22T14:29:35.820Z (generated)
LicenseMIT · demo-eligible
ContaminationNot previously public · No viral exposure recorded

Prompt

The attached module computes order totals and works, but it is exactly the kind of code AI assistants produce: redundant machinery, type laundering, narration comments, a needless wrapper layer. Rewrite it as a clean TypeScript module of the same public behavior (computeTotal, applyDiscount, summarize are called by other code and their signatures must keep accepting the same inputs). Do not change observable behavior. Add focused tests for the discount and rounding edges. Accompany the code with a brief explanation of what you changed and why. The module below is the starting point. Apply the required changes and re-emit the ENTIRE file as one block — never a diff, patch, or excerpt. Seed file `orderTotals.ts`: ```typescript // This module handles order total calculation stuff // It computes the totals for orders and applies discounts as needed import { Order, Item, Result } from './types'; // Step 1: validate the items in the order function validateItems(items: any): boolean { // check that items is valid if (items == null) { return false; } if (!Array.isArray(items)) { return false; } // loop through items and validate each one for (let index = 0; index < items.length; index++) { const currentItem = items[index]; if (typeof currentItem !== 'object') { return false; } if (currentItem.price == undefined) { return false; } if (typeof currentItem.price !== 'number') { return false; } if (currentItem.qty == undefined) { return false; } } return true; } // helper to round money values to 2 decimal places function roundMoney(value: number): number { // rounds to 2 decimals return Math.round(value * 100) / 100; } // computes line total for a single item function computeLineTotal(item: any): number { const price: number = (item as any).price; const qty: number = (item as any).qty as number; const lineTotal = price * qty; return roundMoney(lineTotal); } // wraps computeLineTotal with extra safety function safeLineTotal(item: Item): number { try { return computeLineTotal(item); } catch (e) { return 0; } } export function computeTotal(order: Order): number { // Step 2: compute the total let total = 0; const items = (order as any).items as any[]; if (!validateItems(items)) { return 0; } for (let index = 0; index < items.length; index++) { total = total + safeLineTotal(items[index]); } // Step 3: round and return return roundMoney(total); } export function applyDiscount(total: number, code: string | null | undefined): number { // applies a discount code to the total let result = total; if (code !== null && code !== undefined && code !== '') { if (code === 'SAVE10') { result = result * 0.9; } else if (code === 'SAVE20') { result = result * 0.8; } else if (code === 'HALFOFF') { result = result * 0.5; } else { // unknown code: no discount result = result * 1; } } return roundMoney(result); } // builds a summary object with the total, item count, and discount info export function summarize(order: Order, code?: string | null): Result { const total = computeTotal(order); const discounted = applyDiscount(total, code); const summary = { status: 'success', ok: true, total: total, discounted: discounted, itemCount: (order as any).items.length, savings: roundMoney(total - discounted), }; return summary as unknown as Result; } ``` ## Output contract First, write a brief explanation of your design choices — plain prose, no code fences. Then emit exactly one fenced code block per file, and no other text between or after the blocks: - The FIRST line of every block is that file's marker line: - TypeScript or JavaScript: `// FILE: <path>` - Python: `# FILE: <path>` - A single-file web app is one file named `index.html`, so its marker line is `// FILE: index.html`. - Everything after the marker line is that file complete, from its first line to its last — no diffs, no omissions, no placeholders. - Tag each fence with the file's language, for example ```html, ```typescript, ```python.

Artifact

Form: tree

orderTotals.ts

import { Order, Result } from './types';

const DISCOUNT_FACTORS: Readonly<Record<string, number>> = {
  SAVE10: 0.9,
  SAVE20: 0.8,
  HALFOFF: 0.5,
};

function roundMoney(value: number): number {
  return Math.round(value * 100) / 100;
}

function isBillableList(items: unknown): items is Array<{ price: number; qty: number }> {
  if (items == null || !Array.isArray(items)) {
    return false;
  }

  for (const item of items) {
    if (typeof item !== 'object') {
      return false;
    }
    const { price, qty } = item as { price?: unknown; qty?: unknown };
    if (price == undefined || typeof price !== 'number' || qty == undefined) {
      return false;
    }
  }

  return true;
}

export function computeTotal(order: Order): number {
  const items: unknown = order.items;
  if (!isBillableList(items)) {
    return 0;
  }

  let total = 0;
  for (const item of items) {
    total += roundMoney(item.price * item.qty);
  }
  return roundMoney(total);
}

export function applyDiscount(total: number, code: string | null | undefined): number {
  if (code == null || code === '') {
    return roundMoney(total);
  }
  return roundMoney(total * (DISCOUNT_FACTORS[code] ?? 1));
}

export function summarize(order: Order, code?: string | null): Result {
  const total = computeTotal(order);
  const discounted = applyDiscount(total, code);
  return {
    status: 'success',
    ok: true,
    total,
    discounted,
    itemCount: order.items.length,
    savings: roundMoney(total - discounted),
  } as Result;
}

orderTotals.test.ts

import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { applyDiscount, computeTotal, summarize } from './orderTotals';
import { Order } from './types';

function order(items: Array<{ price: number; qty: number }>): Order {
  return { items } as Order;
}

describe('applyDiscount', () => {
  it('applies only the exact known codes', () => {
    assert.equal(applyDiscount(100, 'SAVE10'), 90);
    assert.equal(applyDiscount(100, 'SAVE20'), 80);
    assert.equal(applyDiscount(100, 'HALFOFF'), 50);
  });

  it('leaves null, undefined, and empty codes undiscounted but still rounded', () => {
    assert.equal(applyDiscount(1.005, null), 1);
    assert.equal(applyDiscount(1.005, undefined), 1);
    assert.equal(applyDiscount(1.005, ''), 1);
  });

  it('does not match case or unknown codes', () => {
    assert.equal(applyDiscount(80, 'save10'), 80);
    assert.equal(applyDiscount(80, 'SAVE10 '), 80);
    assert.equal(applyDiscount(80, 'NONE'), 80);
  });

  it('rounds the discounted amount to cents', () => {
    assert.equal(applyDiscount(10.01, 'SAVE10'), 9.01);
    assert.equal(applyDiscount(0.1, 'SAVE10'), 0.09);
    assert.equal(applyDiscount(0.05, 'HALFOFF'), 0.03);
  });

  it('rounds exact half cents toward +infinity, including negatives', () => {
    assert.equal(applyDiscount(0.025, null), 0.03);
    assert.equal(applyDiscount(-0.025, null), -0.02);
    assert.equal(applyDiscount(-10, 'HALFOFF'), -5);
  });
});

describe('computeTotal rounding', () => {
  it('rounds 1.005 down because the cent product is not an exact half', () => {
    assert.equal(computeTotal(order([{ price: 1.005, qty: 1 }])), 1);
  });

  it('rounds each line before summing', () => {
    const items = [
      { price: 1.005, qty: 1 },
      { price: 1.005, qty: 1 },
    ];
    assert.equal(computeTotal(order(items)), 2);
  });

  it('rounds a binary float sum back to cents', () => {
    const items = [
      { price: 0.1, qty: 1 },
      { price: 0.2, qty: 1 },
    ];
    assert.equal(computeTotal(order(items)), 0.3);
  });
});

describe('summarize', () => {
  it('reports savings from the rounded total, not the raw lines', () => {
    const summary = summarize(
      order([
        { price: 1.005, qty: 1 },
        { price: 1.005, qty: 1 },
      ]),
      'SAVE10',
    );
    assert.deepEqual(summary, {
      status: 'success',
      ok: true,
      total: 2,
      discounted: 1.8,
      itemCount: 2,
      savings: 0.2,
    });
  });
});

Explanation

The public calculations are unchanged: each line is rounded to cents before the lines are summed, the sum is rounded again, and only the three exact discount codes change the factor. Empty or missing codes still skip the discount, while any other non-empty code still multiplies by 1 so it hits the same rounding path. Invalid item lists still yield a zero total, and a null item still throws when its price is read. Summarize still returns the same fields, including an item count taken from the raw list even when the total is zero. I dropped the narration, the try/catch wrapper, and the casts that only papered over the types. Rates live in one table. The tests lock code matching, empty and unknown codes, half-cent rounding toward positive infinity, the 1.005 float edge, and per-line rounding that changes the sum.

Judge detail

No raw judge output is published for this item yet. When it is, it lands under results/raw/ and appears here verbatim; the rubric and protocol are already documented on the Methodology page.