[Javascript AST] 2. Write a simple ESLint rule

Source: Internet
Author: User

What we want to does is checking if user write nested IF statements which actually can combine to one:

// Badif(a) {Console.log (A);} Else {   if(b) {Console.log ("B"); } }//Goodif(a) {Console.log (A);} Else if(b) {Console.log ("B"); } }////////////////////////// Badif(a) {if(b) {Console.log ("B"); } } //Goodif(a) {Console.log (A); if(b) {Console.log ("B"); } } //Goodif(A &&b) {Console.log ("B");} 

Notice that if statement can write with block statement or without block Statem, such as:

if (a)   if (b)    console.log (' B ')

Rule:

Exportdefault function(context) {return{ifstatement (node) {varAncestors =Context.getancestors (), Parent=Ancestors.pop (), grandparent=Ancestors.pop (); if(typeofGrandparent = = = "undefined") {        return; }      if((Parent.type= = = "Blockstatement" &&//If have if () {if () {}}, nested if ' s parent is a blockstatementParent.body.length = = 1 &&//if () {console.log (); if () {}}, we consider this is fineGrandparent.type = = = "Ifstatement") | |//grandparent should be a if statementParent.consequent = = = Node//sometime we write if () something, don ' t has blockstatement, then we check consequent should is the node iteself) {Context.report (node,"Nested IF Statement"); }    }  };}

[Javascript AST] 2. Write a simple ESLint rule

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.