Warning: session_start() [function.session-start]: open(/tmp/sess_upq3vo17er6akbktbni10p8007, O_RDWR) failed: Disk quota exceeded (122) in /home/vipozico/forum.tutorials7.com/qa-include/qa-app-users.php on line 143
Functional Calculator in JavaScript
settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
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
...