8

I have two practically identical functions. The only difference between them are one has + and one has -. These are used about 20 times in each function, so I'd love to make this simpler with a var.

I'm still very new to JavaScript, so I don't know where to start, but something like:

if ( blah blah ){
    var symbol = '-';
} else{
    var symbol = '+';
}

var example = value1 [symbol] value2;

Thanks

FishBasketGordo
  • 22,468
  • 4
  • 58
  • 91
Jake Hills
  • 418
  • 1
  • 5
  • 20

5 Answers5

22

Use this:

var modifier = (blah blah) ? 1 : -1;
var example = value1 + (modifier * value2);
darthmaim
  • 4,709
  • 26
  • 38
6

You could define an object containing functions, keyed by the operator. Something like this:

var operations = {
    '+': function(a, b) { return a + b; },
    '-': function(a, b) { return a - b; }
}

var x = operations[condition ? '+' : '-'](value1, value2);

I think @darthmaim has the nicest method though, but it depends if you need to use other operators, such as *, / or %.

Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
1

why not so:

if ( blah blah ){
    var example = value1 - value2;
} else{
    var example = value1 + value2;
}
Mikhail Timofeev
  • 2,099
  • 14
  • 13
1

Well, you could use eval, but I would use a function like this:

var op;
if (condition) {
    op = function(a, b) { return a - b; };
} else {
    op = function(a, b) { return a + b; };
}

var example = op(value1, value2);
FishBasketGordo
  • 22,468
  • 4
  • 58
  • 91
0
var math = {
    '+' : function(x,y) {return x + y;},
    '-' : function(x,y) {return x - y;}
}

var usePlus = true;
math[usePlus ? '+' : '-'](1,2) // returns 3
aga
  • 27,056
  • 10
  • 81
  • 117