d4-refactor-orders--google-gemini-3-8-flash
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.
| Model | Gemini 3.8 Flash (Google) google/gemini-3.8-flash |
|---|---|
| Task | d4-refactor-orders · refactor · typescript · tests expected |
| Harness | openrouter-chat-completions openrouter-chat-2026-09-22 at temperature 0.3 |
| Generated | 2026-09-22T14:27:59.127Z (generated) |
| License | MIT · demo-eligible |
| Contamination | Not 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
types.ts
export interface Item {
price: number;
qty: number;
}
export interface Order {
items: Item[];
}
export interface Result {
status: string;
ok: boolean;
total: number;
discounted: number;
itemCount: number;
savings: number;
}
orderTotals.ts
import { Order, Item, Result } from './types';
const DISCOUNT_MULTIPLIERS: Record<string, number> = {
SAVE10: 0.9,
SAVE20: 0.8,
HALFOFF: 0.5,
};
export function roundMoney(value: number): number {
return Math.round(value * 100) / 100;
}
function isValidItem(item: unknown): item is Item {
return (
typeof item === 'object' &&
item !== null &&
typeof (item as Item).price === 'number' &&
(item as Item).qty !== undefined
);
}
export function computeTotal(order: Order): number {
const items = order?.items;
if (!Array.isArray(items) || !items.every(isValidItem)) {
return 0;
}
const total = items.reduce(
(sum, item) => sum + roundMoney(item.price * item.qty),
0
);
return roundMoney(total);
}
export function applyDiscount(
total: number,
code: string | null | undefined
): number {
if (!code || !(code in DISCOUNT_MULTIPLIERS)) {
return roundMoney(total);
}
return roundMoney(total * DISCOUNT_MULTIPLIERS[code]);
}
export function summarize(order: Order, code?: string | null): Result {
const total = computeTotal(order);
const discounted = applyDiscount(total, code);
const itemCount = Array.isArray(order?.items) ? order.items.length : 0;
return {
status: 'success',
ok: true,
total,
discounted,
itemCount,
savings: roundMoney(total - discounted),
};
}
orderTotals.test.ts
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { computeTotal, applyDiscount, summarize, roundMoney } from './orderTotals';
import { Order } from './types';
describe('roundMoney', () => {
it('rounds standard floating-point values to 2 decimal places', () => {
assert.strictEqual(roundMoney(10.004), 10.0);
assert.strictEqual(roundMoney(10.005), 10.01);
assert.strictEqual(roundMoney(10.006), 10.01);
});
});
describe('computeTotal', () => {
it('calculates total for standard order', () => {
const order: Order = {
items: [
{ price: 10.5, qty: 2 },
{ price: 5.25, qty: 1 },
],
};
assert.strictEqual(computeTotal(order), 26.25);
});
it('correctly handles floating point addition precision (0.1 + 0.2)', () => {
const order: Order = {
items: [
{ price: 0.1, qty: 1 },
{ price: 0.2, qty: 1 },
],
};
assert.strictEqual(computeTotal(order), 0.3);
});
it('rounds each line total before summing', () => {
const order: Order = {
items: [
{ price: 1.005, qty: 1 }, // rounds to 1.01
{ price: 1.005, qty: 1 }, // rounds to 1.01
],
};
assert.strictEqual(computeTotal(order), 2.02);
});
it('returns 0 for empty, missing, or malformed items', () => {
assert.strictEqual(computeTotal({ items: [] }), 0);
assert.strictEqual(computeTotal({} as unknown as Order), 0);
assert.strictEqual(
computeTotal({ items: [{ price: '10', qty: 1 }] } as unknown as Order),
0
);
assert.strictEqual(
computeTotal({ items: [{ price: 10 }] } as unknown as Order),
0
);
});
});
describe('applyDiscount', () => {
it('applies SAVE10 discount and rounds correctly', () => {
assert.strictEqual(applyDiscount(100, 'SAVE10'), 90);
// 19.99 * 0.9 = 17.991 -> rounds to 17.99
assert.strictEqual(applyDiscount(19.99, 'SAVE10'), 17.99);
});
it('applies SAVE20 discount and rounds correctly', () => {
assert.strictEqual(applyDiscount(100, 'SAVE20'), 80);
// 15.55 * 0.8 = 12.44
assert.strictEqual(applyDiscount(15.55, 'SAVE20'), 12.44);
// 33.33 * 0.8 = 26.664 -> rounds to 26.66
assert.strictEqual(applyDiscount(33.33, 'SAVE20'), 26.66);
});
it('applies HALFOFF discount at half-cent boundaries', () => {
assert.strictEqual(applyDiscount(100, 'HALFOFF'), 50);
// 15.55 * 0.5 = 7.775 -> rounds to 7.78
assert.strictEqual(applyDiscount(15.55, 'HALFOFF'), 7.78);
// 0.01 * 0.5 = 0.005 -> rounds to 0.01
assert.strictEqual(applyDiscount(0.01, 'HALFOFF'), 0.01);
});
it('returns rounded total for unknown, empty, or absent codes', () => {
assert.strictEqual(applyDiscount(49.994, null), 49.99);
assert.strictEqual(applyDiscount(49.994, undefined), 49.99);
assert.strictEqual(applyDiscount(49.994, ''), 49.99);
assert.strictEqual(applyDiscount(49.994, 'INVALID_CODE'), 49.99);
});
});
describe('summarize', () => {
it('builds a complete summary object with accurate savings and item count', () => {
const order: Order = {
items: [
{ price: 9.99, qty: 1 },
{ price: 10.0, qty: 1 },
],
};
const summary = summarize(order, 'SAVE10');
assert.deepStrictEqual(summary, {
status: 'success',
ok: true,
total: 19.99,
discounted: 17.99,
itemCount: 2,
savings: 2.0,
});
});
it('handles orders with zero savings when no discount applies', () => {
const order: Order = {
items: [{ price: 25.5, qty: 2 }],
};
const summary = summarize(order);
assert.deepStrictEqual(summary, {
status: 'success',
ok: true,
total: 51.0,
discounted: 51.0,
itemCount: 1,
savings: 0,
});
});
});
Explanation
I refactored the module to eliminate artificial complexity, type laundering, and noise while preserving all public function signatures and observable arithmetic behavior: 1. Eliminated Type Laundering: Replaced excessive `any` casting and `as unknown as Result` assertions with typed interfaces. The summary object now structurally matches `Result` directly without casting. 2. Removed Redundant Layers: Deleted the `safeLineTotal` wrapper and its empty `try/catch`, along with manual C-style index loops. Item validation is now handled cleanly through an array guard. 3. Declarative Discounts: Replaced the nested `if/else` ladder with a typed discount multiplier lookup table (`DISCOUNT_MULTIPLIERS`), simplifying code lookup and fallback behavior. 4. Preserved Rounding Semantics: Retained per-line and final aggregate two-decimal rounding using `Math.round(val * 100) / 100` to prevent floating-point accumulation discrepancies. 5. Removed Narration Comments: Stripped out procedural comments that merely narrated language syntax, leaving self-documenting code. 6. Focused Edge Testing: Added unit tests covering fractional cent line items, floating-point addition drift (e.g., 0.1 + 0.2), discount half-cent rounding boundaries, empty/malformed inputs, and unknown discount codes.
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.