1

I have a function in JS to compare two integers with an arbitrary operator:

function compare(n1, n2, crit){
    var operator;

    switch (crit) {
        case 'GT':
            operator = '>';
            break;
        case 'GE':
            operator = '>=';
            break;
        case 'EQ':
            operator = '==';
            break;
        case 'LE':
            operator = '<=';
            break;
        case 'LT':
            operator = '<';
            break;
    }
    return eval(n1 + operator + n2);
}

I'm looking for a more elegant approach than the concatenation and the use of the much dreaded eval(). Any ideas?

amacedo
  • 13
  • 2
  • 1
    Is this a simplified example? if not why not simply `case 'EQ': return n1 == n2`; if not see http://stackoverflow.com/questions/5834318/are-variable-operators-possible for a very nice solution. – Alex K. May 23 '12 at 16:41

1 Answers1

4

Why don't you reformat your function like this?

function compare(n1, n2, crit){
    if (crit == 'GT') return n1 > n2;
    if (crit == 'GE') return n1 >= n2;
    if (crit == 'EQ') return n1 == n2;
    if (crit == 'LE') return n1 <= n2;
    if (crit == 'LT') return n1 < n2;
    return false; // default behavior (??)
}
inhan
  • 7,394
  • 2
  • 24
  • 35