How can ternary conditional operators be transformed into if statements?

When dealing with minified code like this,

f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage("error_tooltip"),k.button.v(b.id,f),d({action:"error"}))

Is there a tool available that can automatically convert such a single line of conditional operators into a set of if statements?

For instance:

Initial code:

(i < 0 ? function1() : function2())

Transformed to:

if (i < 0) {
    function1();
} else {
    function2();
}

And another example:

Initial code:

(i < 0 ? function1() : (i === 0 ? function2() : function3()))

Transformed to:

if (i < 0) {
    function1();
} else {
    if (i === 0) {
        function2();
    } else {
        function3();
    }
}

Answer №1

Beginning

f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage("error_tooltip"),k.button.v(b.id,f),d({action:"error"}))

Changing to a more structured format:

if (f && !f.error)
{
    if (k.button.b == k.button.c.G)
    {
        k.button.Q(b, e, f, c, d)
    }
    else
    {
        k.button.b == k.button.c.o && k.button.P(b, e, f, c, d)
    }
}
else
{
    (console.error(f), f = f.error.message || chrome.i18n.getMessage("error_tooltip"), k.button.v(b.id, f), d(
    {
        action: "error"
    }))
}

Using the provided JSBeautifier code:

/*jslint browser: true, vars: true, white: true, maxerr: 50, indent: 4 */
(function (console)
{
    "use strict";

    function transform(string)
    {
        var questionMark = string.indexOf("?");
        var colon = string.indexOf(":", questionMark);

        if (questionMark === -1 || colon === -1)
        {
            return string;
        }

        var condition = string.substring(0, questionMark);
        var expressions = string.substring(questionMark + 1, string.length);
        var trueExpression = null;
        var falseExpression = null;

        console.log("expressions: " + expressions);

        // While looking in pairs, find the location where the colon occurs before the question mark.
        questionMark = expressions.indexOf("?");
        colon = expressions.indexOf(":");
        while ((questionMark !== -1 && colon !== -1) && (questionMark < colon))
        {
            questionMark = expressions.indexOf("?", questionMark + 1);
            colon = expressions.indexOf(":", colon + 1);
        }

        console.log("\t" + "questionMark: " + questionMark);
        console.log("\t" + "colon: " + colon);

        trueExpression = expressions.substring(0, colon);
        falseExpression = expressions.substring(colon + 1, expressions.length);

        console.log("condition: " + condition);
        console.log("trueExpression: " + trueExpression);
        console.log("falseExpression: " + falseExpression);

        console.log("-");

        return ("if (" + condition + ") {\n" + transform(trueExpression) + "\n} else {\n" + transform(falseExpression) + "\n}");
    }

    function unittest()
    {
        console.log(transform("(i < 0 ? function1() : function2())"));
        console.log("---");
        console.log(transform("i < 0 ? function1() : function2()"));
        console.log("---");
        console.log(transform("i < 0 ? function1() : i === 0 ? function2() : function3()"));
        console.log("---");
        console.log(transform("i > 0 ? i === 1 ? function1() : function2() : function3()"));
        console.log("---");
        console.log(transform("i > 0 ? i === 1 ? function1() : i === 2 ? function2() : function3() : function4()"));
        console.log("---");
        console.log(transform("i > 0 ? i === 1 ? function1() : i === 2 ? function2() : function3() : i === 0 ? function4() : function5()"));
        console.log("---");
        console.log(transform("f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage(\"error_tooltip\"),k.button.v(b.id,f),d({action:\"error\"}))"));
    }

    unittest();
}(window.console));

Answer №2

Transform Ternary Operators with Babel

It might seem like old news, but five years on and the question remains relevant.

Faced with the same issue recently, I took matters into my own hands and created a Babel plugin to convert ternary expressions into if-else statements. The plugin aptly named babel-plugin-transform-ternary-to-if-else

Let's take a closer look at how it works.

Demonstration

Here are two code examples demonstrating the transformation carried out by the plugin:

// Input Code
(i < 0 ? function1() : function2())

// Output Code
(function () {
  if (i < 0) {
    return function1();
  }

  return function2();
})();
.
.
.

// More example cases here...

Impressive, right?

You may wonder about the use of Immediately Invoked Function Expressions - wouldn't it be simpler without them?

The Importance of IIFEs

IIFEs are necessary because a conditional expression is an expression, while an if statement is a statement. In order to incorporate a statement within another statement, we need IIFEs.

Although some basic cases can be simplified without IIFEs, not all scenarios allow for such straightforward transformations.

Enter IIFEs!

Looking Ahead

Exciting times lie ahead with proposals like do expressions potentially eliminating the need for verbose IIFEs in the future.

Plugins like babel-plugin-syntax-do-expressions are paving the way for this transition.

Helpful Links

Learn more about babel-plugin-transform-ternary-to-if-else

Explore the do expressions proposal

Get familiar with babel-plugin-syntax-do-expressions

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Gradient on multiple faces in Three.js

I'm currently struggling with creating an HSV cylinder using three.js. I am facing difficulties in properly mapping the gradient to the faces of the cylinder. Initially, I attempted to create my object in this manner: https://i.sstatic.net/WboAE.png ...

Tricks for displaying a dynamic object tooltip in Three.js

Can anyone help me figure out how to create a HUD hint effect for a moving object? I envision something like this: An asteroid is floating through space, and when I click on it, a hint box with information pops up. I've been playing around with thi ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Verify whether a div element is styled in a specific manner

Upon initial load of my website, if the page is maximized or in fullscreen mode, the comBrand div will have specific CSS properties applied. However, during a resize event, I use the .css() function to adjust the properties of this element so it doesn&apos ...

Transfer data between an HTML page and a PHP page hosted on separate locations using jQuery

Below is the code snippet I am currently working on: function send_data() { var a=$("#username").val(); var b=$("#password").val(); $.post("http://localhost/login/login.php", {uname: a, pswd: b}, function(data) { $("#result").html(data); }); ...

What is preventing me from opening this local html page without an IIS Server?

Currently immersed in a passion project that can be found at https://github.com/loganhenson/jsrpg This project has been a collaborative effort with a friend, utilizing Visual Studio Professional for development and testing it on my local IIS server. Init ...

Tips for modifying jsFiddle code to function properly in a web browser

While similar questions have been asked before, I am still unable to find a solution to my specific issue. I have a functional code in jsFiddle that creates a table and allows you to select a row to color it red. Everything works perfectly fine in jsFiddle ...

Is there a way to display the contents of a zipped file using an HTML IFrame?

Can I display the contents of a zipped file in an HTML iframe? For example: My_File.pdf.zip contains My_File.pdf. I currently have something like this <iframe src="/path of the folder/My_File.pdf.zip" /> The src attribute points to the zipped file ...

Learn how to update a form dynamically using the Ajax.BeginForm feature

I am currently working on updating a form within my application using Ajax.BeginForm. The update process is functioning correctly, however, upon executing the function in the controller, it redirects to a view with the controller function name displayed. ...

The Vue JS Option element requires the "selected" attribute to be utilized as a property instead

I'm attempting to automatically have an option selected if the "selected" property is present on the option object. Here is my code snippet: <template> <select v-model="model" :placeholder="placeholder"> <option v-for="opt ...

I am experiencing issues with my $ajax request

After running the code snippet below: websiteUrl= "http://192.168.2.171/LoginAuthentication"; $.ajax({ url: 'websiteUrl', type: 'GET', success: function(response) { var title = $(response.responseText).find('a. ...

The function .then is not compatible with AngularJS

I have a service that is responsible for loading data. angular.module('App').service('daysService', ['$http','$q',function($http,$q) { var days = []; return { loadDay: function() { ...

Send data in JSON format along with an identifier using Jquery AJAX

I am having trouble sending JSON data along with 2 IDs using a jQuery AJAX post. Despite my efforts, I can't seem to get it working. Here is the code snippet in question: try { var surveyID = localStorage.getItem("surveyId"); var userDetails ...

How can I export an ES Object in Node.JS to an NPM package?

I am currently facing a challenge involving an ES5 object/function that I want to integrate into an NPM package. This particular object is within a namespace defined as MY_NAMESPACE.myObject = function(){...} where MY_NAMESPACE is simply an object. Typic ...

Trigger the opening of a class or window upon pressing the button

Good evening, I'm attempting to create a functionality where pressing a specific button will open a window. However, I am unsure of how to achieve this using CSS classes. My initial thought was to add a new class in the CSS file and call it every ti ...

What methods can I use to display or conceal certain content based on the user's location?

I'm looking to display specific content exclusively to local users. While there are APIs available for this purpose, I'm not sure how to implement them. I'm interested in creating a feature similar to Google Ads, where ads are tailored base ...

In the event of any unexpected errors while utilizing an API, a ticket will be automatically generated on Jira through the use of Vue.js

After successfully hitting the API through Postman and creating a ticket on Jira, I encountered a CORS error when attempting to do the same using an index.js file in VueJS. The flow is unclear to me as generating a demo error results in nothing being sho ...

Error in TypeScript when utilizing generic callbacks for varying event types

I'm currently working on developing a generic event handler that allows me to specify the event key, such as "pointermove", and have typescript automatically infer the event type, in this case PointerEvent. However, I am encountering an error when try ...

Alter Text Using Typewriter

Recently, I have been experimenting with code on my glitch website, trying to create typewriter text. Thanks to help from a user on StackOverflow, I was able to achieve this effect successfully. However, I am now facing a new challenge. My goal is to make ...

"After completing the survey form, the User Details form is displayed upon clicking the submit button

In my Quiz, each question loads on a separate page with clickable options. Some questions may have multiple answers, including an "Others" option. At the end of the quiz, users need to fill out a form. Although I've created a survey form, I'm fa ...