📜 ⬆️ ⬇️

Expanded Ternary Operator Application

Familiar to all operator construction: var a = (condition)? c: d; can be used more efficiently ...

For example, to perform functions on the condition:
condition ? exec1() : exec2; or just one function: condition ? exec1() : null; condition ? exec1() : null; or condition ? exec1() : 0; condition ? exec1() : 0; You can optimize even more by using the && operator. Example: condition && exec1();
There is one problem in using such a construction: the impossibility of performing several functions at the same time under one of the conditions, i.e. option condition ? exec1(); exec2(); : 0; condition ? exec1(); exec2(); : 0; is wrong.
The solution may be:
condition ?
(function() {
exec1();
exec2();
})()
:0;

Second solution: condition ? exec1() && exec2() && exec3() : 0; condition ? exec1() && exec2() && exec3() : 0; much more compact, but alas, it has a major drawback: if one of the executed functions returns false, the interpreter stops the execution of the following, the same problem will arise if you use the operator ||, the interpreter will stop at the first true result.
The solution is in the use of the operator's bitwise: condition ? exec1() | exec2() | exec3() : 0; condition ? exec1() | exec2() | exec3() : 0; or condition && ( exec1() | exec2() | exec3() );
As they say, voila and convenient and compact.

PS It is also possible to use a comma as a function separator:
condition ? ( exec1() , exec2() , exec3() ) :0;

Based on paulbakaus.com

')

Source: https://habr.com/ru/post/13388/


All Articles