Pav*_*l T 4 javascript operators ternary
I have a piece of code:
if (foo > bar) {
baz = foo - bar
} else {
baz = foo + bar
}
Run Code Online (Sandbox Code Playgroud)
I have a question if I can somehow shorten this code to a single line, something like
PSEUDOCODE:
baz = foo (foo > bar ? + : -) bar
Run Code Online (Sandbox Code Playgroud)
Real code I'd like to shorten
if (gradientStartH > gradientEndH) {
h = gradientStartH - Math.abs(gradientStartH - gradientEndH) / arr.length * i
} else {
h = gradientStartH + Math.abs(gradientStartH - gradientEndH) / arr.length * i
}
Run Code Online (Sandbox Code Playgroud)
Thanks!
You could convert the check to a number or take -1 as factor.
baz = foo + (foo > bar || -1) * bar
Run Code Online (Sandbox Code Playgroud)
The cleanest approach is to use an object with the operands and a check for getting the operands.
op = {
true: function (a, b) { return a + b; }, // add
false: function (a, b) { return a - b; } // sub
}
baz = op[foo > bar](foo, bar);
Run Code Online (Sandbox Code Playgroud)