Tuesday, February 23, 2016

IF() to Ternary Operator conversion in Javascript

<script>
function myFunction() {
   
    var str = "IF((4+2)==5,true,false)";
    str = str.replace(/\s/g, '');
    var length = str.length;
    while (str.lastIndexOf("(") != -1 ) {
       
        var start = str.lastIndexOf("(");
        var strEnd = str.substring(start,str.length);
        var end = start + strEnd.indexOf(")");
        var tempWithIf = str.substring(start-2, end+1);
        var tempWithBrack = str.substring(start, end+1);
        var temp = str.substring(start+1, end);
        var tempArr = temp.split(',');
        var strReplace;
        if (tempArr.length == 3) {
            strReplace = tempArr[0] + "?" + tempArr[1] + ":" +  tempArr[2];
            str = str.replace(tempWithIf,strReplace);
        } else {
           
             strReplace = tempWithBrack.replace('(','{');
             strReplace = strReplace.replace(')','}');
             str = str.replace(tempWithBrack,strReplace);
        }
     
    }
    str = str.replace(/{/g,'(');
    str = str.replace(/}/g,')');
    console.log(eval(str));
   
}
</script>

Thanks to Ramarajan

7 comments:

  1. I really had a great time with your post! essay writers I am looking forward to read more blog post regarding this! Well written!

    ReplyDelete
  2. Really structured and useful information. essay paper
    And everything is clear, thanks. I looked through some posts and must say, they are very interesting. Best regards, essay writing service .

    ReplyDelete
  3. Good site you have got here.It’s difficult to find high quality writing like yours these days. I honestly appreciate people like you! Take care.
    casio

    ReplyDelete
  4. We are a third party technical support service. Avast Customer Support is here to help you out with the whole procedure to Download Avast Antivirus online, We not only fix your Avast Support related issues but will guide with how to get started with your new Avast product once it gets installed successfully.We at Avast Tech Support provides service to protect your PC from potential online threats and external attacks like viruses, Trojans, malwares, spywares and phishing scams. And Avast Refund. Call on our Avast Phone Number.

    At www.office.com/setup we will help you out with Office Setup including the whole procedure to Download Microsoft Office online, We not only fix your MS office setup related issues, we will also guide with how to get started with your new Office 2016 or Office 365 product once it gets installed successfully.

    ReplyDelete

Salesforce - Generate dynamic inner query to fetch parent and related child records

Use Case: In many scenarios, we need to clone the records with related child records. Issue / Limitation: We may simply use the "cl...