9

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,904
  • 4
  • 58
  • 91
Jake Hills
  • 428
  • 1
  • 5
  • 21

5 Answers5

23

Use this:

var modifier = (blah blah) ? 1 : -1;
var example = value1 + (modifier * value2);
darthmaim
  • 4,970
  • 1
  • 27
  • 40
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
  • 331,213
  • 40
  • 305
  • 339
1

why not so:

if ( blah blah ){
    var example = value1 - value2;
} else{
    var example = value1 + value2;
}
Mikhail Timofeev
  • 2,169
  • 15
  • 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,904
  • 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,954
  • 13
  • 86
  • 121