eslint-plugin-de-morgan
Version:
ESLint plugin for transforming negated boolean expressions via De Morgan’s laws
88 lines (87 loc) • 2.51 kB
JavaScript
import { isBinaryExpression } from './is-binary-expression.js'
/**
* Determines whether a given expression is used in a boolean context.
*
* Boolean contexts include conditions in control flow statements (`if`,
* `while`, `for`), logical expressions (`&&`, `||`), explicit boolean coercions
* (`!!`, `Boolean(expr)`), and comparison operations (`===`, `!==`, `<`, `>`).
*
* @param node - The AST node to check.
* @param [_context] - The ESLint rule context (technical argument).
* @returns True if the expression is used in a boolean context.
*/
function hasBooleanContext(node, _context) {
return node.parent ?
isControlFlowBooleanContext(node.parent) ||
isBooleanOperation(node.parent) ||
isBooleanFunction(node.parent)
: false
}
/**
* Checks if the given node is part of a control flow structure that expects a
* boolean value.
*
* These structures include:
*
* - `if (expr) {...}`
* - `while (expr) {...}`
* - `for (; expr; ) {...}`
* - `expr ? A : b` (ternary)
* - Logical expressions (`&&`, `||`)
* - Explicit coercion via `!!expr`.
*
* @param parent - The parent node in the AST.
* @returns True if the node is in a boolean context.
*/
function isControlFlowBooleanContext(parent) {
return booleanControlFlowNodes.has(parent.type)
}
var booleanControlFlowNodes = /* @__PURE__ */ new Set([
'ConditionalExpression',
'LogicalExpression',
'DoWhileStatement',
'UnaryExpression',
'WhileStatement',
'ForStatement',
'IfStatement',
])
/**
* Checks if the given node is part of an operation that always returns a
* boolean value. Supported operators:
*
* - Comparison: `===`, `!==`, `==`, `!=`, `<`, `>`, `<=`, `>=`
* - Type checking: `in`, `instanceof`.
*
* @param parent - The parent node in the AST.
* @returns True if the node is a part of a binary comparison.
*/
function isBooleanOperation(parent) {
return isBinaryExpression(parent) && booleanOperators.has(parent.operator)
}
var booleanOperators = /* @__PURE__ */ new Set([
'instanceof',
'===',
'!==',
'==',
'!=',
'<=',
'>=',
'in',
'<',
'>',
])
/**
* Checks if the given node is passed to a function that explicitly converts it
* to a boolean.
*
* @param parent - The parent node in the AST.
* @returns True if the node is passed to `Boolean()`.
*/
function isBooleanFunction(parent) {
return (
parent.type === 'CallExpression' &&
parent.callee.type === 'Identifier' &&
parent.callee.name === 'Boolean'
)
}
export { hasBooleanContext }