eslint-plugin-de-morgan
Version:
ESLint plugin for transforming negated boolean expressions via De Morgan’s laws
72 lines (71 loc) • 2.65 kB
JavaScript
import { repository } from '../package.json.js'
import { createTestWithParameters } from '../utils/create-test-with-parameters.js'
import { hasNegationInsideParens } from '../utils/has-negation-inside-parens.js'
import { isInTruthinessContext } from '../utils/is-in-truthiness-context.js'
import { getStatementSafeFix } from '../utils/get-statement-safe-fix.js'
import { needsParentParens } from '../utils/needs-parent-parens.js'
import { hasBooleanContext } from '../utils/has-boolean-context.js'
import { applyToProperty } from '../utils/apply-to-property.js'
import { sanitizeCode } from '../utils/sanitize-code.js'
import { isPureGroup } from '../utils/is-pure-group.js'
import { isNegated } from '../utils/is-negated.js'
import { isDisjunction } from '../utils/is-disjunction.js'
import { transform } from '../utils/transform.js'
import { not } from '../utils/not.js'
import { or } from '../utils/or.js'
var no_negated_disjunction_default = {
create: context => ({
UnaryExpression: node => {
if (
createTestWithParameters(node, context)(
isNegated,
applyToProperty('argument', isDisjunction),
isPureGroup,
or(hasBooleanContext, not(hasNegationInsideParens)),
)
) {
let fixedExpression = transform({
expressionType: 'disjunction',
shouldWrapInParens: needsParentParens(node, '&&'),
canStripNegation: isInTruthinessContext(node),
context,
node,
})
if (fixedExpression) {
let safeFix = getStatementSafeFix({
fix: fixedExpression,
context,
node,
})
let originalExpression = context.sourceCode.getText(node)
context.report({
data: {
fixed: sanitizeCode(safeFix ?? fixedExpression),
original: sanitizeCode(originalExpression),
},
fix: fixer =>
safeFix === null ? null : fixer.replaceText(node, safeFix),
messageId: 'convertNegatedDisjunction',
node,
})
}
}
},
}),
meta: {
docs: {
description:
'Transforms the negation of a disjunction !(A || B) into the equivalent !A && !B according to De Morgan’s law',
url: `https://github.com/${repository}/blob/main/docs/no-negated-disjunction.md`,
recommended: true,
},
messages: {
convertNegatedDisjunction:
'Replace negated disjunction `{{ original }}` with `{{ fixed }}`',
},
type: 'suggestion',
fixable: 'code',
schema: [],
},
}
export { no_negated_disjunction_default as default }