MediumPro challengeJavaScriptTypeScript

Open/Closed Principle

TypeScriptClean CodeSOLIDOCP

Software entities should be open for extension, closed for modification. Adding a new case should not require editing existing code.

// dirty — adding a new shape requires editing solve
function solve(type: string, ...dims: number[]): number {
  if (type === 'circle') return Math.PI * dims[0] ** 2;
  if (type === 'rect')   return dims[0] * dims[1];
  if (type === 'tri')    return 0.5 * dims[0] * dims[1];
  throw new Error('Unknown shape');
}

Refactor so each shape has its own area() method. Create createCircle(r), createRect(w, h), createTriangle(b, h). Then solve(type, ...dims) just instantiates the right shape and calls .area() — no if chains needed when adding new shapes.

Sample tests

Test #1Circle r=5
Input: ["circle",5]
Output: 78.53981633974483
Test #2Rect 6×4
Input: ["rect",6,4]
Output: 24
Test #3Triangle base=10 height=5
Input: ["tri",10,5]
Output: 25