[Javascript AST] 2. Introduction: Write a simple ESLint rule
发布日期:2021-09-05 12:41:18 浏览次数:2 分类:技术文章

本文共 1541 字,大约阅读时间需要 5 分钟。

What we want to do 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: 

We can export a default 'create' function. 

export default function(context) {  return {     // rules  }}// the same asmodule.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");      }    }  };}

 

 

 

转载地址:https://blog.csdn.net/weixin_34239169/article/details/85943584 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:17秋 软件工程 结对项目 第二次作业
下一篇:Win10 UWP系列:关于错误 0x80073CF9及一个小bug的解决

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年03月28日 13时08分18秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章