if-exp
Conditional (if) expressions for JavaScript
NPM
npm install
Usage
const iff = ; const result = ;
Motivations
Some languages implement conditionals (and other well known statements) as expressions, so we can write:
val res = if(condition){
'result 1'
} else if(secondCondition) {
'result 2'
} else if(thirdCondition) {
'result 3'
} else {
'result 4'
}
While in JavaScript, conditional expressions can be achieve using ternary operators. Multiple conditions are sometimes hard to read using ternary:
var res = condition ? 'result 1' : secondCondition ? 'result 2' : thirdCondition ? 'result 3' : 'result 4';
Here is how to write the same thing with iff:
const res = ;
How to do lazy-statements evaluation in JavaScript
const res = ;
The issue with the above code, is that statement1
, statement2
and statement3
functions will be executed no matter the value of condition
and condition2
. To only execute one or the other we can use functions:
const res = ;
Now, if-exp will yield a function depending on the conditions and we directly execute it resulting in a lazy statement evaluation.
How if-exp supports lazy condition evaluation
const res = ;
The issue with the above code is that conditionalFn1
and conditionalFn2
will be both executed. Since if-exp v2+, you can specify a predicate function as a condition and it will be evaluated or not depending on the previous conditions:
const res = ;
Changelog
Donate
I maintain this project in my free time, if it helped you please support my work via paypal or Bitcoins, thanks a lot!