Basic CLI Calculator
NodeJS
Medium
4 views
Problem Description
Create a CLI that reads two numbers and an operator and prints result.
Input Format
stdin: a op b
Output Format
Print result.
Constraints
Support + - * /.
Official Solution
const fs = require('fs');
const s = fs.readFileSync(0, 'utf8').trim();
if (!s) process.exit(0);
const parts = s.split(/\\s+/);
const a = Number(parts[0]);
const op = parts[1];
const b = Number(parts[2]);
let out = NaN;
if (op === '+') out = a + b;
else if (op === '-') out = a - b;
else if (op === '*') out = a * b;
else if (op === '/') out = b === 0 ? 'DIV0' : a / b;
console.log(String(out));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!