Easy refactor ternary conditions to if else
danielpdev
Posted on March 10, 2020
Have you ever had a pain on understanding ternary conditions put in the code by others colleagues that have left the project?
Well, if you think understanding a simple ternary it's easy for you, look at the following example:
const [a1, a2, a3] = [true, 3, true];
const a4 = 0;
const [a5, a6, a7] = [false, 2, false];
const result = a1 ? a4 : a2 ? a4 : a5 ? a6 : a7 ? a4 :
a5 ? a6 : a7 ? a4 : a5 ? a6 : a7 ? a4 : a5 ? a6 : a7;
console.log(result);
What will be the value of result
?
Take your time....
.............
...........
.........
.......
.....
...
..
.
R: 0
Now imagine that we have a lot more expressions and not just numbers and booleans. Yeah, not the best day of changing something in the old codebase.
But there is a package that auto refactors to an IIFE(Immediately Invoked Function Expression)
easy and more readable.
Its a babel plugin wrote a while ago
Now, after using ternary to if else we get:
var a = function () {
if (a1) {
return a4;
}
return function () {
if (a2) {
return a4;
}
return function () {
if (a5) {
return a6;
}
return function () {
if (a7) {
return a4;
}
return function () {
if (a5) {
return a6;
}
return function () {
if (a7) {
return a4;
}
return function () {
if (a5) {
return a6;
}
return function () {
if (a7) {
return a4;
}
return function () {
if (a5) {
return a6;
}
return a7;
}();
}();
}();
}();
}();
}();
}();
}();
}();
Enjoy and keep on coding!
Posted on March 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.