Skip to content

Commit

Permalink
feat: make it faster with early returns ⚡️
Browse files Browse the repository at this point in the history
  • Loading branch information
GSTJ committed May 12, 2023
1 parent 8e39ffd commit d86a810
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 19 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"linting",
"code quality"
],
"version": "1.0.2",
"version": "1.0.3",
"main": "lib/index.js",
"scripts": {
"prepack": "npmignore --auto --commentLines=autogenerated && npm run build",
Expand Down
34 changes: 16 additions & 18 deletions src/rules/jsx-explicit-boolean.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,37 +12,35 @@ module.exports = {
return {
LogicalExpression(node) {
// We're only interested in && operators
if (node.operator !== '&&') {
return;
}
if (node.operator !== '&&') return;

// We're only interested in JSX elements on the right-hand side
if (node.right.type !== 'JSXElement') {
return;
}
if (node.right.type !== 'JSXElement') return;

const { left } = node;

const isExplicitBooleanConversion = left.type === 'CallExpression'
&& left.callee.type === 'Identifier'
&& left.callee.name === 'Boolean';
if (isExplicitBooleanConversion) return;

const isBooleanLiteral = left.type === 'Literal' && typeof left.value === 'boolean';
if (isBooleanLiteral) return;

const isBooleanVariable = left.type === 'Identifier'
&& context.getScope().variables.some((variable) => variable.name === left.name && variable.defs.some((def) => def.type === 'Variable' && typeof def.node.init.value === 'boolean'));
if (isBooleanVariable) return;

if (!isExplicitBooleanConversion && !isBooleanLiteral && !isBooleanVariable) {
context.report({
node,
messageId: 'booleanConversion',
fix(fixer) {
return fixer.replaceTextRange(
[left.range[0], left.range[1]],
`Boolean(${context.getSourceCode().getText(left)})`,
);
},
});
}
context.report({
node,
messageId: 'booleanConversion',
fix(fixer) {
return fixer.replaceTextRange(
[left.range[0], left.range[1]],
`Boolean(${context.getSourceCode().getText(left)})`,
);
},
});
},
};
},
Expand Down

0 comments on commit d86a810

Please sign in to comment.