MirrorMirror
MirrorMirror

Reputation: 188

javascript conditional logical operator

I have the following:

var cond1 = (a>b) ? true: false;
var cond2 = (d<c) ? true: false;
var cond3 = (e==f) ? true: false;

var found = cond1 && cond2 && cond3;

I want to be able in an elegant way to substitute the && logical operator for another like || and do this programmatically, as in a sort of "variable" operator. Because I don't want to do something like:

var found1 = cond1 && cond2 && cond3;
var found2 = cond1 || cond2 || cond3;
var found3 = (cond1 && cond2) || cond3;

and then switch/if depending on what choice the user has selected from the interface, it's not elegant.

How can I do this ? (if possible)

Thank you in advance

Upvotes: 1

Views: 162

Answers (3)

Jamiec
Jamiec

Reputation: 136074

I would start with something like a method which can take a string (AND/OR) and an array of bool delegates and perform the action(s)

function operator(which, ...args)
{
    switch(which.toUpperCase())
    {
        case "AND": return args.every(a => a());
        case "OR": return args.some(a => a());
        default: throw "Invalid operator " + which;
    }
}

var a = 1;
var b = 2;
var c = 3;
var d = 4;
var e = 5;
var f = 5;

var cond1 = () => (a>b) ;
var cond2 = () => (d<c) ;
var cond3 = () => (e==f);

var found1 = operator("and",cond1,cond2,cond3);
var found2 = operator("or",cond1,cond2,cond3);
var found3 = operator("or", () => operator("and",cond1,cond2), cond3);
console.log(found1,found2,found3)

From there its easy enough to build up dynamically.

References

Upvotes: 2

Hriday Modi
Hriday Modi

Reputation: 2081

I think elegant way of writing this is code should be readable and easy to understand. Making a logic complex to achieve simple thing doesn't make sense in my opinion. Things which kept simple and clean is less bug prone than complex logic, it gives us the confidence on our code.

Here you can store && and || in variable and can pass to the function.

var cond1 = (2>3);
var cond2 = (5<9);
var cond3 = (5==7);

const compareConditions = (operator, operand1, operand2) => {
  switch(operator){
    case "&&": {
      return operand1 && operand2;
    }
    case "||":{
       return operand1 || operand2;
    }
    default:{
      return false;
    }
  }
}

console.log(compareConditions("||", compareConditions("&&" , cond1, cond2), cond3));

Upvotes: 1

Chris Disley
Chris Disley

Reputation: 1345

Depending on complexity, I'd either go with something similar to what you already have, or if there are a lot of options, I might go with some sort of flags/bitmask solution.

There are some good examples of this in JavaScript here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

Upvotes: 0

Related Questions