[Javascript AST] 2. Introduction: Write a simple ESLint rule
JavaScript Write Simple rule Introduction eslint AST
2023-09-14 08:59:18 时间
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"); } } }; }
相关文章
- javascript 基础_JavaScript高级编程
- 用javascript教你打造一个免费的PC微信机器人《五》微信群发
- HTML的注释与JavaScript注释及快捷键「建议收藏」
- javascript对象数组内元素排序
- JavaScript 进阶
- JavaScript学习总结(十七)——Javascript原型链的原理详解编程语言
- JavaScript学习总结(五)——Javascript中==和===的区别详解编程语言
- JavaScript的document和window对象详解编程语言
- 用Write函数写入Linux文件(write函数linux)
- javascript监听手机返回键详解编程语言
- Jsprime——一款JavaScript静态安全分析工具
- JavaScript获取用户客户端操作系统版本
- JavaScript验证18位身份证号码最后一位正确性的实现代码
- javascript中cookie对象用法实例分析