d4-refactor-orders--openai-gpt-6-astra

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.

ModelGPT-6 Astra (OpenAI) openai/gpt-6-astra
Taskd4-refactor-orders · refactor · typescript · tests expected
Harnessopenrouter-chat-completions openrouter-chat-2026-09-22 at temperature 0.3
Generated2026-09-22T14:27:09.066Z (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 type { Order, Item, Result } from './types';

function validateItems(items: unknown): boolean {
  if (!Array.isArray(items)) {
    return false;
  }

  for (let index = 0; index < items.length; index++) {
    const item = items[index];

    // Null elements intentionally retain the original validation-time error.
    if (
      typeof item !== 'object' ||
      item.price == null ||
      typeof item.price !== 'number' ||
      item.qty == null
    ) {
      return false;
    }
  }

  return true;
}

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

function lineTotal(item: Item): number {
  try {
    return roundMoney(item.price * item.qty);
  } catch {
    return 0;
  }
}

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

  let total = 0;
  for (let index = 0; index < items.length; index++) {
    total += lineTotal(items[index]);
  }

  return roundMoney(total);
}

export function applyDiscount(
  total: number,
  code: string | null | undefined,
): number {
  switch (code) {
    case 'SAVE10':
      return roundMoney(total * 0.9);
    case 'SAVE20':
      return roundMoney(total * 0.8);
    case 'HALFOFF':
      return roundMoney(total * 0.5);
    case null:
    case undefined:
    case '':
      return roundMoney(total);
    default:
      return roundMoney(total * 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),
  };
}

orderTotals.test.ts

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

// Deliberately exercise runtime inputs beyond the static Order contract.
function orderWith(items: unknown): Order {
  return { items } as Order;
}

test('recognized discount codes apply their exact factors', () => {
  assert.equal(applyDiscount(100, 'SAVE10'), 90);
  assert.equal(applyDiscount(100, 'SAVE20'), 80);
  assert.equal(applyDiscount(100, 'HALFOFF'), 50);
});

test('absent and unrecognized codes still round without discounting', () => {
  const codes = [
    undefined,
    null,
    '',
    'UNKNOWN',
    'save10',
    ' SAVE10',
    'SAVE10 ',
    'toString',
    '__proto__',
  ];

  for (const code of codes) {
    assert.equal(applyDiscount(12.346, code), 12.35);
  }
});

test('discount rounding preserves small amounts and negative ties', () => {
  const cases: Array<[number, string, number]> = [
    [0.05, 'SAVE10', 0.05],
    [0.05, 'SAVE20', 0.04],
    [0.05, 'HALFOFF', 0.03],
    [-0.05, 'HALFOFF', -0.02],
    [0.01, 'HALFOFF', 0.01],
    [-0.01, 'HALFOFF', -0],
  ];

  for (const [total, code, expected] of cases) {
    assert.equal(applyDiscount(total, code), expected);
  }
});

test('rounding retains native floating-point behavior', () => {
  assert.equal(applyDiscount(1.005, undefined), 1);
  assert.equal(applyDiscount(2.675, undefined), 2.68);
  assert.equal(applyDiscount(-1.125, undefined), -1.12);

  assert.equal(
    computeTotal(orderWith([{ price: 1.005, qty: 1 }])),
    1,
  );
});

test('zero, signed zero, and non-finite totals retain their behavior', () => {
  for (const code of [undefined, null, '', 'UNKNOWN', 'SAVE10', 'SAVE20', 'HALFOFF']) {
    assert.equal(applyDiscount(0, code), 0);
    assert.equal(applyDiscount(-0, code), -0);
    assert.equal(applyDiscount(Infinity, code), Infinity);
    assert.equal(applyDiscount(-Infinity, code), -Infinity);
    assert.ok(Number.isNaN(applyDiscount(NaN, code)));
  }
});

test('each line is rounded before summation', () => {
  assert.equal(
    computeTotal(orderWith([
      { price: 0.005, qty: 1 },
      { price: 0.005, qty: 1 },
    ])),
    0.02,
  );

  assert.equal(
    computeTotal(orderWith([{ price: 0.005, qty: 2 }])),
    0.01,
  );
});

test('the accumulated total is rounded again', () => {
  assert.equal(
    computeTotal(orderWith([
      { price: 0.1, qty: 1 },
      { price: 0.2, qty: 1 },
    ])),
    0.3,
  );
  assert.equal(computeTotal(orderWith([])), 0);
});

test('quantities retain JavaScript coercion and per-line error handling', () => {
  assert.equal(
    computeTotal(orderWith([
      { price: 1.25, qty: '2' },
      { price: 1, qty: true },
      { price: 10, qty: Symbol('quantity') },
      {
        price: 10,
        qty: {
          valueOf() {
            throw new Error('Cannot convert quantity');
          },
        },
      },
    ])),
    3.5,
  );

  assert.ok(Number.isNaN(
    computeTotal(orderWith([{ price: 1, qty: 'not a number' }])),
  ));
});

test('validation retains its existing rejection and exception behavior', () => {
  for (const items of [
    undefined,
    null,
    {},
    [undefined],
    [{ price: '1', qty: 1 }],
    [{ price: 1, qty: null }],
  ]) {
    assert.equal(computeTotal(orderWith(items)), 0);
  }

  assert.throws(() => computeTotal(orderWith([null])), TypeError);

  const throwingPrice = {
    get price(): number {
      throw new Error('Cannot read price');
    },
    qty: 1,
  };

  assert.throws(
    () => computeTotal(orderWith([throwingPrice])),
    /Cannot read price/,
  );
});

test('summary uses the rounded total and rounds savings', () => {
  assert.deepEqual(
    summarize(orderWith([
      { price: 0.1, qty: 1 },
      { price: 0.2, qty: 1 },
    ]), 'SAVE10'),
    {
      status: 'success',
      ok: true,
      total: 0.3,
      discounted: 0.27,
      itemCount: 2,
      savings: 0.03,
    },
  );
});

test('summary preserves raw item counts and missing-items errors', () => {
  assert.deepEqual(summarize(orderWith([{ price: '1', qty: 1 }])), {
    status: 'success',
    ok: true,
    total: 0,
    discounted: 0,
    itemCount: 1,
    savings: 0,
  });

  assert.throws(() => summarize(orderWith(null)), TypeError);
});

Explanation

Removed the wrapper layer, redundant assertions, and narration comments. The module retains the original validation quirks, quantity coercion, per-line error handling, and `Math.round` behavior rather than introducing stricter validation or different money arithmetic. Tests use Node’s built-in test runner and cover discount boundaries, floating-point rounding, signed zero, and key compatibility cases.

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.