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