0

I know I can simply use an if else statement to have the math done for me, and could even create a function that could be called either way depending on the need, but I am trying to based on math simply store either + or - as a variable so it can execute

for example

plusOrMinus = +

5 + plusOrMinus + 5 = 10 
7
  • well yes and you can use eval() but its quite dangerous. Commented Jun 6, 2013 at 2:34
  • @Mahan I would love to see an example with eval() and hear the reasoning for why it's "dangerous" Commented Jun 6, 2013 at 2:36
  • I have heard people say eval() is dangerous, but I know people can inline edit javascript with modern browsers; and whatnot, I just see no danger of it other than someone injecting something into their specific browser. Commented Jun 6, 2013 at 2:36
  • 1
    @g00ch—in that case just have a sign or direction parameter that is either +1 or -1, then multiply your final value by the sign. In a game, usually performance matters and eval is slow (though perhaps not slow enough to matter in your case). Commented Jun 6, 2013 at 2:54
  • 1
    @g00ch—regarding eval, it is strongly warned against because it was widely misused in early scripting where the language wasn't understood, e.g. eval('document.all(' + elementName + ')'). There is nothing inherently "evil" or dangerous, it's just considered poor practice as the alternatives are faster, less to write and have fewer side effects (from memory, eval can have scope issues but I 'm a little rusty on that because I almost never use it). Commented Jun 6, 2013 at 2:58

4 Answers 4

3

I'm not sure what kind of situation you're in, but wouldn't multiplying by 1 or -1 suffice?

plusOrMinus = 1
5 + (plusOrminus * 5) = 10

plusOrMinus = -1
5 + (plusOrminus * 5) = 0
Sign up to request clarification or add additional context in comments.

1 Comment

Seems to me that 5 - 5 = 0, not -10.
2

No, but it is possible to create a function that wraps the given operator(s):

function add(a, b) { return a + b };
function sub(a, b) { return a - b };

var op = add;  // look, functions are just objects!
op(5, 5) // -> 10
var op = sub;
op(7, 3) // -> 4

Well, how does this help us? Just expand it!

function fold (arr, fn) {
    var r = arr[0];
    for (var i = 1; i < arr.length - 1; i++) {
        r = fn(r, arr[i]);
    }
    return r;
}
fold([1,2,3], add) // -> 6

Comments

1

You can store 1 or -1, and multiply, like this:

var plusOrMinus;
var Result;

plusOrMinus = 1;

Result = (5 + 5) * plusOrMinus; // 10

plusOrMinus = -1;

Result = (5 + 5) * plusOrMinus; // -10

Comments

1

You probably need eval()

plusOrMinus  = '+'

eval(5+plusorMinus+5);

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.