F
F
Faber Estello2015-02-10 22:29:02
JavaScript
Faber Estello, 2015-02-10 22:29:02

JavaScript How to pass one of the parameters to a function - an object?

Prompt how to transfer object as parameter f-ii and how the call looks.
Task:
Write a calculator function for adding positive numbers, which takes 3 parameters: the first number, the second number, the name of the operation (plus, minus, multiply, divide).

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Melnikov, 2015-02-11
@senselessV7

function calc(x, y, operation) {
  var operations = {
    plus: function(x, y) { return x + y },
    minus: function(x, y) { return x - y },
    multiply: function(x, y) { return x * y },
    divided: function(x, y) { return x / y },
  }
  return operations[operation] && operations[operation](x, y);
}

calc(10, 20, "plus"); // 30

W
werdender, 2015-02-11
@werdender

Could it be something else like this:

function calc(a, b, operation) {
    if(['+',' -', '*', '/'].indexOf(operation) < 0) {
        throw new Error('invalid operation'); 
    }
    return eval(parseFloat(a) + operation + parseFloat(b));
};
calc(5, 2, '*') //10

(About eval is devil in the know)

K
Keyten, 2015-02-13
@Keyten

Also, can you be a little short?
calc=(a,b,o)=>eval((+a)+o+(+b));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question