[Javascript AST] 2. Write a simple ESLint rule

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript AST] 2. Write a simple ESLint rule相关的知识,希望对你有一定的参考价值。

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

// BAD
if (a) {
  console.log("a");
} else { 
  if (b) {
    console.log("b");
  } 
}

// GOOD
if (a) {
  console.log("a");
} else if (b) {
    console.log("b");
  } 
}

////////////////////////

// BAD
if (a) {
   if (b) {
    console.log("b");
   } 
} 

// GOOD
if (a) {
  console.log("a");
   if (b) {
    console.log("b");
   } 
} 

// GOOD
if (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:

export default function(context) {
  return {
    IfStatement(node) {
      var ancestors = context.getAncestors(),
        parent = ancestors.pop(),
        grandparent = ancestors.pop();

      if (typeof grandparent === "undefined") {
        return;
      }

      if (
        (parent.type === "BlockStatement" && // if has if() { if() {}}, nested if‘s parent is a BlockStatement
        parent.body.length === 1 && // if() { console.log(); if() {} }, we consider this is fine
          grandparent.type === "IfStatement") || // grandparent should be a if statement
        parent.consequent === node // sometime we write if() something, don‘t have blockstatement, then we check consequent should be the node iteself
      ) {
        context.report(node, "nested if statement");
      }
    }
  };
}

 

 

 

以上是关于[Javascript AST] 2. Write a simple ESLint rule的主要内容,如果未能解决你的问题,请参考以下文章

[Javascript AST] 0. Introduction: Write a simple BabelJS plugin

JavaScript 二进制的 AST

AST抽象语法树——最基础的javascript重点知识,99%的人根本不了解

操作JavaScript的AST

AST抽象语法树——最基础的JavaScript重点知识

AST抽象语法树 Javascript版