Skip to content Skip to sidebar Skip to footer

Javascript -- Pass A Boolean (or Bitwise) Operator As An Argument?

In C# there are various ways to do this C# Pass bitwise operator as parameter specifically the 'Bitwise.Operator.OR' object, but can something like this be done in JavaScript? For

Solution 1:

You can create a object with keys as operators and values as functions. You will need Bracket Notation to access the functions.

You can use Rest Parameters and some() and every() for more than two parameters for &&,||.

For the bitwise operator or +,-,*,/ multiple values you can use reduce()

const check = {
  '>':(n1,n2) => n1 > n2,
  '<':(n1,n2) => n1 < n2,
  '&&':(...n) => n.every(Boolean),
  '||':(...n) => n.some(Boolean),
  '&':(...n) => n.slice(1).reduce((ac,a) => ac & a,n[0])
}

console.log(check['>'](4,6)) //falseconsole.log(check['<'](4,6)) /trueconsole.log(check['&&'](2 < 5, 8 < 10, 9 > 2)) //trueconsole.log(check['&'](5,6,7)  === (5 & 6 & 7))

Solution 2:

You can do the exact same thing suggested by the linked answers:

functioncheck(num1, num2, op) {
  returnop(num1, num2);
}

// Use it like thischeck(3, 7, (x, y) => x > y);

You can also create an object that provides all of these operations:

constOperators = {
  LOGICAL: {
    AND: (x, y) => x && y,
    OR: (x, y) => x || y,
    GT: (x, y) => x > y,
    // ... etc. ...
  },
  BITWISE: {
    AND: (x, y) => x & y,
    OR: (x, y) => x | y,
    XOR: (x, y) => x ^ y,
    // ... etc. ...
  }
};

// Use it like thischeck(3, 5, Operators.BITWISE.AND);

Solution 3:

How about something like:

 function binaryOperation( obj1, obj2, operation ) {
     return operation( obj1, obj2 );
 }
 function greaterThan( obj1, obj2 ) {
    return obj1 > obj2 ;
 }
 function lessThan( obj1, obj2 ) {
    return obj1 < obj2 ;
 }
 alert( binaryOperation( 10, 20, greaterThan ) );
 alert( binaryOperation( 10, 20, lessThan ) );

Solution 4:

It is not possible. But 1 way you can approach this is by doing the following:

function evaluate(v1, v2, op) {
    let res = "" + v1 + op + v2;
    returneval(res)
}
console.log(evaluate(1, 2, "+"));
# outputs 3

But be careful while passing args as they will be evaluated which is dangerous if some hacky code is passed to the function.

Post a Comment for "Javascript -- Pass A Boolean (or Bitwise) Operator As An Argument?"