简体   繁体   中英

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

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

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)); 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM