AzLearn

تمرين إعادة البناء

Simple Calculator

أعد كتابة حاسبة TypeScript صغيرة تستخدم union types و switch.

typescript ~10 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
type Operation = "add" | "subtract" | "multiply" | "divide";

function calculate(left: number, operation: Operation, right: number): number {
  switch (operation) {
    case "add":
      return left + right;
    case "subtract":
      return left - right;
    case "multiply":
      return left * right;
    case "divide":
      if (right === 0) {
        throw new Error("Cannot divide by zero");
      }
      return left / right;
  }
}

const examples: Array<[number, Operation, number]> = [
  [8, "add", 4],
  [8, "subtract", 4],
  [8, "multiply", 4],
  [8, "divide", 4],
];

for (const [left, operation, right] of examples) {
  console.log(`${left} ${operation} ${right} = ${calculate(left, operation, right)}`);
}
اكتب هنا