EasyJavaScriptTypeScript

DRY — Don't Repeat Yourself

TypeScriptClean CodeDRYRefactoring

The functions below share ~80% of their logic. Any change to the formatting must be made in 3 places.

// dirty
function formatUSD(amount: number): string {
  if (amount < 0) return '-$' + Math.abs(amount).toFixed(2);
  return '$' + amount.toFixed(2);
}
function formatEUR(amount: number): string {
  if (amount < 0) return '-€' + Math.abs(amount).toFixed(2);
  return '€' + amount.toFixed(2);
}
function formatGBP(amount: number): string {
  if (amount < 0) return '-£' + Math.abs(amount).toFixed(2);
  return '£' + amount.toFixed(2);
}

Refactor by extracting a generic formatCurrency(amount, symbol) helper. Then solve(amount, type) dispatches to the right formatter — 'formatUSD', 'formatEUR', or 'formatGBP'.

Sample tests

Test #1USD positive
Input: [10.5,"formatUSD"]
Output: "$10.50"
Test #2EUR negative
Input: [-10.5,"formatEUR"]
Output: "-€10.50"
Test #3GBP zero
Input: [0,"formatGBP"]
Output: "£0.00"