1

I currently have a large switch statement:

switch (arg) {
    case '+':
        equals = num1 + num2;
        break;
    case '-':
        equals = num1 - num2;
        break;
    case '*':
        equals = num1 * num2;
        break;
    case '/':
        equals = num1 / num2;
        break;
    case '%':
        equals = num1 % num2;
        break;
    default:
        error();
        return;
}

I wanted to know if there was anyway that I could do something like

equals = num1 /** Do the operation defined by a variable */ num2

Or something like that so I dont have the large switch statement I wasn't even sure where to start looking for something like this since things like "Dynamic operators in js" doesnt bring up what im looking for, any help is apreciated.

1 Answer 1

1

You can try using object with methods.

const operations = {
  "+": (a, b) => a + b,
  "-": (a, b) => a - b,
  "*": (a, b) => a * b,
  "/": (a, b) => a / b,
  "%": (a, b) => a % b,
};

const action = (op, a, b) => operations[op](a, b);

console.log(action("+", 5, 6));
console.log(action("/", 4, 2));

Creating function dynamically. Refer MDN for details and security concerns.

Alternavely, you can create function dynamically.

function createOperation(op) {
    return new Function('return arguments[0]' + op + 'arguments[1]'); 
}

const add = createOperation('+');
const sub = createOperation('-');

console.log(add(5, 6))
console.log(sub(5, 2))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.