settingsAccountsettings
Menusettings

Q: Functional Calculator in JavaScript

+3 votes

Write a JavaScript program that receives two (2) variables and an operator and performs a calculation between the variables, using the operator.

Store the different functions in variables and pass them to your calculator.

The input comes as three arguments – two (2) numbers, and a string, representing the operator.

Examples:

Input: 2, 4, '+'

Output: 6


Input: 3, 3, '/'

Output: 1


Input: 18, -1, '*'

Output: -18

The output should be printed on the console.

asked in JavaScript category by user john7

1 Answer

+1 vote

Here's my calc:

function calculate(a, b, op) {
    let calc = function (a, b, op) {
        return op(a, b);
    };
    let add = function (a, b) {
        return a + b;
    };
    let subtract = function (a, b) {
        return a - b;
    };
    let multiply = function (a, b) {
        return a * b;
    };
    let divide = function (a, b) {
        return a / b;
    };

    switch (op) {
        case "+":
            return calc(a, b, add);
        case "-":
            return calc(a, b, subtract);
        case "*":
            return calc(a, b, multiply);
        case "/":
            return calc(a, b, divide);

    }
}

console.log(calculate(6, 2, "/"));

 

answered by user Jolie Ann
...