码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript AST] 2. Write a simple ESLint rule

时间:2017-09-25 22:09:51      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:node   ted   length   ant   efi   db2   explorer   func   ide   

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

标签:node   ted   length   ant   efi   db2   explorer   func   ide   

原文地址:http://www.cnblogs.com/Answer1215/p/7593975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!