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"); } } };}