ESLint Plugin De Morgan

VersionGitHub starsDownloads per weekLicense

The idea came up at work. I kept running into conditions with a negation in front of the parentheses, and every time I had to unpack them in my head. It seemed to me that a linter could do this just fine.

ESLint Plugin De Morgan rewrites such conditions according to De Morgan’s laws. These are two laws of Boolean algebra:

Before:

JavaScript
if (!(user.role === 'admin' || user.isOwner)) {
  throw new Error('Access denied')
}

After:

JavaScript
if (user.role !== 'admin' && !user.isOwner) {
  throw new Error('Access denied')
}

The plugin has two rules: no-negated-conjunction for !(a && b) and no-negated-disjunction for !(a || b).

The plugin doesn’t change how the code behaves. For example, it writes the negation of count >= 10 as !(count >= 10), not count < 10. If count is NaN, both comparisons return false, so that replacement would break the condition.

How to start using it?

Install ESLint and the plugin:

Bash
npm install --save-dev eslint eslint-plugin-de-morgan

Add the recommended config to eslint.config.js:

JavaScript
import deMorgan from 'eslint-plugin-de-morgan'

export default [deMorgan.configs.recommended]

Both rules fix the code automatically. Run ESLint with the --fix flag, and the plugin will rewrite all the expressions itself.