EasyJavaScriptTypeScript

Replace Magic Numbers

TypeScriptClean CodeReadabilityRefactoring

Magic numbers make code unreadable. What does 86400000 mean? What about 0.2?

// dirty
function solve(priceInCents: number, ageInMs: number): { discounted: number; ageInDays: number } {
  const discounted = priceInCents * (1 - 0.2);
  const ageInDays = ageInMs / 86400000;
  return { discounted: Math.round(discounted), ageInDays: Math.floor(ageInDays) };
}

Refactor by introducing named constants so the intent is self-documenting.
The output must remain identical.

Sample tests

Test #11000 cents with 20% discount = 800; 1 day in ms = 1 day
Input: [1000,86400000]
Output: {"ageInDays":1,"discounted":800}
Test #2Zero age → 0 days
Input: [500,0]
Output: {"ageInDays":0,"discounted":400}
Test #32 days in ms, price of 0
Input: [0,172800000]
Output: {"ageInDays":2,"discounted":0}