Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add prefer-nullish-coalescing rule #1388

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions docs/rules/prefer-nullish-coalescing.md
@@ -0,0 +1,27 @@
# Prefer the nullish coalescing operator(`??`) over the logical OR operator(`||`)

fisker marked this conversation as resolved.
Show resolved Hide resolved
The [nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) only coalesces when the value is `null` or `undefined`, it is safer than [logical OR operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR) which coalesces on any [falsy value](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).

## Fail

```js
const foo = bar || value;
```

```js
foo ||= value;
```

```js
if (foo || value) {}
```

## Pass

```js
const foo = bar ?? value;
```

```js
foo ??= value;
```
2 changes: 2 additions & 0 deletions index.js
Expand Up @@ -102,6 +102,8 @@ module.exports = {
'unicorn/prefer-module': 'error',
'unicorn/prefer-negative-index': 'error',
'unicorn/prefer-node-protocol': 'error',
// TODO: Enable this by default when targeting Node.js 14.
'unicorn/prefer-nullish-coalescing': 'off',
'unicorn/prefer-number-properties': 'error',
// TODO: Enable this by default when targeting a Node.js version that supports `Object.hasOwn`.
'unicorn/prefer-object-has-own': 'off',
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Expand Up @@ -98,6 +98,7 @@ Configure it in `package.json`.
"unicorn/prefer-module": "error",
"unicorn/prefer-negative-index": "error",
"unicorn/prefer-node-protocol": "error",
"unicorn/prefer-nullish-coalescing": "off",
"unicorn/prefer-number-properties": "error",
"unicorn/prefer-object-has-own": "off",
"unicorn/prefer-optional-catch-binding": "error",
Expand Down Expand Up @@ -202,6 +203,7 @@ Each rule has emojis denoting:
| [prefer-module](docs/rules/prefer-module.md) | Prefer JavaScript modules (ESM) over CommonJS. | ✅ | 🔧 | 💡 |
| [prefer-negative-index](docs/rules/prefer-negative-index.md) | Prefer negative index over `.length - index` for `{String,Array,TypedArray}#slice()`, `Array#splice()` and `Array#at()`. | ✅ | 🔧 | |
| [prefer-node-protocol](docs/rules/prefer-node-protocol.md) | Prefer using the `node:` protocol when importing Node.js builtin modules. | ✅ | 🔧 | |
| [prefer-nullish-coalescing](docs/rules/prefer-nullish-coalescing.md) | Prefer the nullish coalescing operator(`??`) over the logical OR operator(`||`). | | | 💡 |
| [prefer-number-properties](docs/rules/prefer-number-properties.md) | Prefer `Number` static properties over global ones. | ✅ | 🔧 | 💡 |
| [prefer-object-has-own](docs/rules/prefer-object-has-own.md) | Prefer `Object.hasOwn(…)` over `Object.prototype.hasOwnProperty.call(…)`. | | 🔧 | |
| [prefer-optional-catch-binding](docs/rules/prefer-optional-catch-binding.md) | Prefer omitting the `catch` binding parameter. | ✅ | 🔧 | |
Expand Down
79 changes: 79 additions & 0 deletions rules/prefer-nullish-coalescing.js
@@ -0,0 +1,79 @@
'use strict';
const {getStaticValue} = require('eslint-utils');
const {matches} = require('./selectors/index.js');
const {isBooleanNode} = require('./utils/boolean.js');

const ERROR = 'error';
const SUGGESTION = 'suggestion';
const messages = {
[ERROR]: 'Prefer `{{replacement}}` over `{{original}}`.',
[SUGGESTION]: 'Use `{{replacement}}`'
};

const selector = matches([
'LogicalExpression[operator="||"]',
'AssignmentExpression[operator="||="]'
]);

/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
return {
[selector](node) {
if (
[node.parent, node.left, node.right].some(node => node.type === 'LogicalExpression') ||
isBooleanNode(node) ||
isBooleanNode(node.left)
) {
return;
}

const {left} = node;

const staticValue = getStaticValue(left, context.getScope());
if (staticValue) {
const {value} = staticValue;
if (!(typeof value === 'undefined' || value === null)) {
return;
}
}

const isAssignment = node.type === 'AssignmentExpression';
const originalOperator = isAssignment ? '||=' : '||';
const replacementOperator = isAssignment ? '??=' : '??';
const operatorToken = context.getSourceCode()
.getTokenAfter(
node.left,
token => token.type === 'Punctuator' && token.value === originalOperator
);

const messageData = {
original: originalOperator,
replacement: replacementOperator
};
return {
node: operatorToken,
messageId: ERROR,
data: messageData,
suggest: [
{
messageId: SUGGESTION,
data: messageData,
fix: fixer => fixer.replaceText(operatorToken, replacementOperator)
}
]
};
}
};
};

module.exports = {
fisker marked this conversation as resolved.
Show resolved Hide resolved
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer the nullish coalescing operator(`??`) over the logical OR operator(`||`).'
},
messages,
hasSuggestions: true
}
};
39 changes: 34 additions & 5 deletions rules/utils/boolean.js
Expand Up @@ -3,7 +3,6 @@
const isLogicalExpression = require('./is-logical-expression.js');

const isLogicNot = node =>
node &&
node.type === 'UnaryExpression' &&
node.operator === '!';
const isLogicNotArgument = node =>
Expand All @@ -13,14 +12,22 @@ const isBooleanCallArgument = node =>
isBooleanCall(node.parent) &&
node.parent.arguments[0] === node;
const isBooleanCall = node =>
node &&
node.type === 'CallExpression' &&
node.callee &&
!node.optional &&
node.callee.type === 'Identifier' &&
node.callee.name === 'Boolean' &&
node.arguments.length === 1;
const isObjectIsCall = node =>
node.type === 'CallExpression' &&
!node.optional &&
node.callee.type === 'MemberExpression' &&
!node.callee.computed &&
!node.callee.optional &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'Object' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'is';
const isVueBooleanAttributeValue = node =>
node &&
node.type === 'VExpressionContainer' &&
node.parent.type === 'VAttribute' &&
node.parent.directive &&
Expand All @@ -32,6 +39,25 @@ const isVueBooleanAttributeValue = node =>
node.parent.key.name.rawName === 'else-if' ||
node.parent.key.name.rawName === 'show'
);
const isBooleanLiteral = node =>
node.type === 'Literal' &&
typeof node.value === 'boolean';
// https://github.com/estree/estree/blob/master/es5.md#binaryoperator
const comparisonOperators = new Set([
'==',
'!=',
'===',
'!==',
'<',
'<=',
'>',
'>=',
'in',
'instanceof'
]);
const isComparison = node =>
node.type === 'BinaryExpression' &&
comparisonOperators.has(node.operator);

/**
Check if the value of node is a `boolean`.
Expand All @@ -44,7 +70,10 @@ function isBooleanNode(node) {
isLogicNot(node) ||
isLogicNotArgument(node) ||
isBooleanCall(node) ||
isBooleanCallArgument(node)
isBooleanCallArgument(node) ||
isBooleanLiteral(node) ||
isComparison(node) ||
isObjectIsCall(node)
) {
return true;
}
Expand Down
46 changes: 46 additions & 0 deletions test/prefer-nullish-coalescing.mjs
@@ -0,0 +1,46 @@
import {getTester} from './utils/test.mjs';

const {test} = getTester(import.meta);

test.snapshot({
valid: [
'const a = 0; const foo = a || 1;',
'const a = {b: false}; const foo = a.b || 1;',
'const foo = 0n || 1;',
'const foo = "" || 1;',
'const foo = `` || 1;',
'const foo = NaN || 1;',
// Boolean
'const foo = !(a || b)',
'const foo = Boolean(a || b)',
'if (a || b);',
'const foo = (a || b) ? c : d;',
'while (a || b);',
'do {} while (a || b);',
'for (;a || b;);',
// Left is boolean
'const foo = false || a',
'const foo = !bar || a',
'const foo = a == 1 || bar',
'const foo = a != 1 || bar',
'const foo = a === b || a === c',
'const foo = a !== b || bar',
'const foo = a < 1 || bar',
'const foo = a <= 1 || bar',
'const foo = a > 1 || bar',
'const foo = a >= 1 || bar',
'const foo = Object.is(a, -0) || a < 0',
'const foo = ("key" in object) || bar',
'const foo = (object instanceof Foo) || Array.isArray(object)',
// Mixed
'const foo = a || (b && c)',
'const foo = (a || b) && c',
'const foo = a ?? (b || c)',
'const foo = (a ?? b) || c'
],
invalid: [
'const foo = a || b',
'foo ||= b',
'const foo = (( a )) || b'
]
});
47 changes: 47 additions & 0 deletions test/snapshots/prefer-nullish-coalescing.mjs.md
@@ -0,0 +1,47 @@
# Snapshot report for `test/prefer-nullish-coalescing.mjs`

The actual snapshot is saved in `prefer-nullish-coalescing.mjs.snap`.

Generated by [AVA](https://avajs.dev).

## Invalid #1
1 | const foo = a || b

> Error 1/1

`␊
> 1 | const foo = a || b␊
| ^^ Prefer \`??\` over \`||\`.␊
--------------------------------------------------------------------------------␊
Suggestion 1/1: Use \`??\`␊
1 | const foo = a ?? b␊
`

## Invalid #2
1 | foo ||= b

> Error 1/1

`␊
> 1 | foo ||= b␊
| ^^^ Prefer \`??=\` over \`||=\`.␊
--------------------------------------------------------------------------------␊
Suggestion 1/1: Use \`??=\`␊
1 | foo ??= b␊
`

## Invalid #3
1 | const foo = (( a )) || b

> Error 1/1

`␊
> 1 | const foo = (( a )) || b␊
| ^^ Prefer \`??\` over \`||\`.␊
--------------------------------------------------------------------------------␊
Suggestion 1/1: Use \`??\`␊
1 | const foo = (( a )) ?? b␊
`
Binary file added test/snapshots/prefer-nullish-coalescing.mjs.snap
Binary file not shown.