Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 example:

function check(num1, num2, op) {
    return num1 op num2; //just an example of what the output should be like
}

check(1,2, >); //obviously this is a syntax error, but is there some kind of other object or bitwise operator of some kind I can plug into the place of ">" and change the source function somehow?
like image 587
B''H Bi'ezras -- Boruch Hashem Avatar asked Jun 18 '26 10:06

B''H Bi'ezras -- Boruch Hashem


2 Answers

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)) //false
console.log(check['<'](4,6)) /true
console.log(check['&&'](2 < 5, 8 < 10, 9 > 2)) //true

console.log(check['&'](5,6,7)  === (5 & 6 & 7))
like image 110
Maheer Ali Avatar answered Jun 19 '26 23:06

Maheer Ali


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

function check(num1, num2, op) {
  return op(num1, num2);
}

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

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

const Operators = {
  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 this
check(3, 5, Operators.BITWISE.AND);
like image 30
Sean Vieira Avatar answered Jun 19 '26 23:06

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!