Daniel Rodriguez
@daniel_rodriguez • 1 months ago
Make an AI or coding agent pin current behavior with tests, refactor in small steps, and never edit a test to make it pass, with preserved bugs listed.
targetgoalcode{{target}}{{goal}}{{code}}target: getDiscount() in src/pricing/discount.js (Jest)
goal: Replace the nested ifs with a lookup table and small pure functions so new tiers are a one-line change.
code:
```js
function getDiscount(user, cart) {
let d = 0
if (user) {
if (user.isEmployee) {
d = 30
} else {
if (user.tier === "gold") {
d = cart.total > 5000 ? 15 : 10
} else if (user.tier === "silver") {
d = cart.total > 5000 ? 8 : 5
} else {
if (cart.total > 5000) d = 3
}
}
if (user.firstOrder && d < 10) d = 10
}
return d
}
````js`cart must still not throw for employees or for user = null.!user. Re-run all tests.baseDiscount(user, cart). Re-run all tests.ifs with a lookup. My first draft used a plain object, TIER_RATES[user.tier]. The 'constructor' test would fail, because the lookup returns Object itself. Reverted, and used a Map.if (firstOrder && d < 10) with Math.max. Re-run all tests.cart.total before the employee check would break the "employee never reads cart" test, so the total is read inside baseDiscount, after that check.`js`Map entry, and the first-order rule is one line instead of being tangled with the tiers."platinum" silently gets the no-tier rate.> rather than >=).cart throws a TypeError.'constructor' test, which caught a real prototype-lookup bug in the obvious refactor. Stating the invariant, including errors thrown, protected a behavior nobody would have thought to keep (employees never touch cart). Listing preserved bugs separates cleanup from fixes, so each can be reviewed on its own.