Jump to content

Passing arithmetic operators in function arguments..


Rod

Recommended Posts

Is there a way of passing arithmetic operators via a functions' parameters and/or arguments. e.g

##########################################################################
function doTheMath(a, b, doThis) {
    return a  doThis  b;    //  have this evaluate to... a + b or a * b ...etc as appropriate.
}

var theResult = doTheMath(4,10, + );     // the "+" could be any of the arithmetic operators.
##########################################################################

I know it's possible to do it with multiple "if" statements or "switch" statement or callbacks (yes..i watched a video on callbacks on...."a well known video sharing website",  but is there an easier (smaller code) way of doing it.

Just curious....I'm a newbe.

 

Link to comment
Share on other sites

No, you can't.

I would recommend making multiple functions, one for each operation, just to keep things organized, but if you absolutely need to do it all in the same function you can pass a string to indicate which operation to do.
 

function operate(a, b, operator) {
  switch(operator) {
    case "+": return a + b;
    case "-": return a - b;
    case "*": return a * b;
    case "/": return a / b;
    default: return 0;
  }
}

 

Link to comment
Share on other sites

Just in case someone is interested, I managed to get it to work. I've tried passing the "+" without the quotes and then doing toString() on the receiving parameter but that did not work but as it in now, it does work.

function doMath(a,b,doThis){
    return    eval(a.toString().concat(doThis, b.toString()));
}

var theResult = doMath(50, 20, "+");
alert(theResult);

Link to comment
Share on other sites

That's very inefficient. eval() should never be used.

Why exactly do you want a function that does a math operation when you can simply do the operation right where you would be calling the function.

// Short and efficient
var theResult = 50 + 20;

// Long and inefficient
var theResult = doMath(50, 20, "+");

 

Link to comment
Share on other sites

well.... using that (your) logic i might as well put 70 in "theResult" in the first place.

I'm not trying to do something in particular with this, i was just wondering "can it be done", and so....now knowing that it can be done, it might come in useful in the future. (not necessarily on a math problem) . I don't doubt your comment that "eval" is inefficient"......i have no idea either way, I'm new to javascript, but... it's available and it worked.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...