Skip to content

#238 Fix Basic Calculator

Adam Kubiś edited this page Oct 28, 2026 · 1 revision

238 Fix Basic Calculator

Mubashir created a function that takes two numbers a and b and an operator o.

His function should return the result of the corresponding mathematical function on both numbers.

If the operator is not one of the specified characters +, -, /, *, the function should return -1.

Current source and tests | Catalog | Testing and tooling

Run this solution

From the cloned repository root, after installing dependencies:

node "Edabit/238 Fix Basic Calculator.js"

Assertions are kept alongside the implementation and throw on failure. A successful run exits with code 0. Run every exercise with npm test or both lint and tests with npm run check.

Current implementation and tests

This is the complete executable file, including its imports and inline test cases. Run it from the repository, not as an isolated file copied out of the wiki. Line endings and trailing whitespace are normalized; executable tokens are unchanged.

//Mubashir created a function that takes two numbers a and b and an operator o.
//His function should return the result of the corresponding mathematical function on both numbers.
//If the operator is not one of the specified characters +, -, /, *, the function should return -1.
function basicCalculator(a, o, b) {
	if (o === "+") {
		return a + b;
	} else if (o === "-") {
			return a - b;
		}
		if (o === "/" && b !== 0) {
			return a / b;
		}
	if (o === "*") {
		return a * b;
	}
	return null;
}
import { assertEquals } from '../testHelper.js';
assertEquals(basicCalculator(2, '+', 4), 6)
assertEquals(basicCalculator(12, '-', 6), 6)
assertEquals(basicCalculator(18, '/', 2), 9)
assertEquals(basicCalculator(6, '*', 4), 24)
assertEquals(basicCalculator(2, '/', 0), null)
assertEquals(basicCalculator(2, 'x', 4), null)
assertEquals(basicCalculator(2, 'o', 4), null)
assertEquals(basicCalculator(12, '-', 2), 10)
assertEquals(basicCalculator(17, '*', 2), 34)

Clone this wiki locally