Look up arithmetic operations by their symbol and apply them, with typed function values.
What to build
A calculator that evaluates simple expressions.
Requirements
- Store
+,-,*and/as functions of type(a: number, b: number) => numberin a record. - For each expression
A OP B, print the result rounded to at most two decimal places (useMath.round(r * 100) / 100). - Print
cannot divide by zerofor division by 0 andunknown operator OPfor any other operator.
Input
Line 1: n. Then n lines A OP B, separated by single spaces; A and B are numbers.
Output
n lines.
Constraints
1 ≤ n ≤ 50; |A|, |B| ≤ 10^6.
Example
Input:
4
7 * 6
10 / 4
3 - 5
2 + 0.5
Output:
42
2.5
-2
2.5
Why it works
With the operations typed as functions of two numbers, every lookup result can be called safely once it is known to exist, and the record makes adding an operation a one-line change.
Examples
Example 1 · Input
4 7 * 6 10 / 4 3 - 5 2 + 0.5
Expected output
42 2.5 -2 2.5
Example 2 · Input
3 10 / 3 1 / 0 2 ^ 3
Expected output
3.33 cannot divide by zero unknown operator ^
Hints
Hint 1
Keep the four operations in a Record<string, (a: number, b: number) => number>.
Hint 2
Check for an unknown operator and for division by zero before calling the operation.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
type Operation = (a: number, b: number) => number;
const operations: Record<string, Operation> = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
};
const n = Number(read());
for (let i = 0; i < n; i++) {
const [a, op, b] = read().split(" ");
const operation = operations[op];
if (!operation) {
console.log("unknown operator " + op);
} else if (op === "/" && Number(b) === 0) {
console.log("cannot divide by zero");
} else {
console.log(Math.round(operation(Number(a), Number(b)) * 100) / 100);
}
}