zoukankan      html  css  js  c++  java
  • [Javascript AST] 2. Introduction: 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: 

    We can export a default 'create' function. 

    export default function(context) {
      return {
         // rules
      }
    }
    
    // the same as
    
    module.exports = {
      create: (context) => {
        return {
            // rules
         }
      }  
    }
    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");
          }
        }
      };
    }

  • 相关阅读:
    python基础--函数的命名空间and作用域
    MYSQL基础常识
    python基础--函数
    python基础--文件相关操作
    python基础--字符编码以及文件操作
    homebrew长时间停在Updating Homebrew 这个步骤
    python基础--数据类型的常用方法2
    python基础--数据类型的常用方法1
    python基础--定义装饰器(内置装饰器)
    angular创建组件
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7593975.html
Copyright © 2011-2022 走看看