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 rule prefer-nullish-coalescing #343

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ These rules are purely matters of style and are quite subjective.
* [prefer-immutable-method](docs/rules/prefer-immutable-method.md): Prefer using methods that do not mutate the source parameters, e.g. `_.without` instead of `_.pull`.
* [prefer-invoke-map](docs/rules/prefer-invoke-map.md): Prefer using `_.invoke` over `_.map` with a method call inside.
* [prefer-map](docs/rules/prefer-map.md): Prefer `_.map` over `_.forEach` with a `push` inside.
* [prefer-nullish-coalescing](docs/rules/prefer-nullish-coalescing.md): Prefer `??` when doing a comparison with a non-nil value as test.
* [prefer-reject](docs/rules/prefer-reject.md): Prefer `_.reject` over filter with `!(expression)` or `x.prop1 !== value`
* [prefer-thru](docs/rules/prefer-thru.md): Prefer using `_.prototype.thru` in the chain and not call functions in the initial value, e.g. `_(x).thru(f).map(g)...`
* [prefer-wrapper-method](docs/rules/prefer-wrapper-method.md): Prefer using array and string methods in the chain and not the initial value, e.g. `_(str).split(' ')...`
Expand Down
25 changes: 25 additions & 0 deletions docs/rules/prefer-nullish-coalescing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Prefer nullish coalescing over checking a ternary with !isNil.

When checking if a variable is not nil as a test for a ternary equation, it's more coincise to just use the nullish coalescing operator.

## Rule Details

This rule takes no arguments.

The following patterns are considered warnings:

```js
const myExpression = !isNil(myVar) ? myVar : myOtherVar;
```

The following patterns are not considered warnings:

```js
const myExpression = !isNil(myVar) ? mySecondVar : myThirdVar;

const myExpression = myVar ?? myOtherVar;
```


## When Not To Use It
If you do not want to enforce using nullish coalescing.
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const recommended = {
'lodash/prefer-map': 2,
'lodash/prefer-matches': [2, 3],
'lodash/prefer-noop': 2,
'lodash/prefer-nullish-coalescing': 2,
'lodash/prefer-over-quantifier': 2,
'lodash/prefer-reject': [2, 3],
'lodash/prefer-some': [2, {includeNative: true}],
Expand Down
53 changes: 53 additions & 0 deletions src/rules/prefer-nullish-coalescing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* @fileoverview Rule to prefer nullish coalescing over checking a ternary with !isNil.
*/
'use strict'

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

const getDocsUrl = require('../util/getDocsUrl')

module.exports = {
meta: {
type: 'problem',
schema: [],
docs: {
url: getDocsUrl('prefer-nullish-coalescing')
},
fixable: 'code'
},

create(context) {
const {getLodashContext} = require('../util/lodashUtil')
const lodashContext = getLodashContext(context)

function getTextOfNode(node) {
if (node) {
if (node.type === 'Identifier') {
return node.name
}
return context.getSourceCode().getText(node)
}
}

const visitors = lodashContext.getImportVisitors()
visitors.ConditionalExpression = function (node) {
const statement = node.test
if (statement.operator === '!') {
if (statement.argument && statement.argument.callee && statement.argument.callee.name && statement.argument.callee.name === 'isNil') {
const argument = getTextOfNode(statement.argument.arguments[0])
const consequent = getTextOfNode(node.consequent)
const alternate = getTextOfNode(node.alternate)
if (argument === consequent) {
context.report({node, message: 'Prefer nullish coalescing over checking a ternary with !isNil.', fix(fixer) {
return fixer.replaceText(node, `${argument} ?? ${alternate}`)
}})
}
}
}
}
return visitors
}
}
31 changes: 31 additions & 0 deletions tests/lib/rules/prefer-nullish-coalescing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use strict'

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

const rule = require('../../../src/rules/prefer-nullish-coalescing')
const ruleTesterUtil = require('../testUtil/ruleTesterUtil')

// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------

const ruleTester = ruleTesterUtil.getRuleTester()
const {withDefaultPragma, fromMessage} = require('../testUtil/optionsUtil')
const toErrorObject = fromMessage('Prefer nullish coalescing over checking a ternary with !isNil.')
ruleTester.run('prefer-nullish-coalescing', rule, {
valid: [
{code: 'const myExpression = myVar ?? myOtherVar;', parserOptions: {ecmaVersion: 2020}},
'const myExpression = !isNil(myVar) ? mySecondVar : myThirdVar;',
'const myExpression = myOtherVar ? myVar : !isNil(myVar);',
'const myExpression = myOtherVar ? !isNil(myVar) : myVar;',
{code: 'const myExpression = (myVar ?? myOtherVar) ? doThis() : doThat();', parserOptions: {ecmaVersion: 2020}},
{code: 'const myExpression = (myVar?.thisProp ?? myOtherVar[thatProp]) ? doThis() : doThat();', parserOptions: {ecmaVersion: 2020}},
{code: 'myVar ?? myOtherVar;', parserOptions: {ecmaVersion: 2020}}
].map(withDefaultPragma),
invalid: [
{code: 'const myExpression = !isNil(myVar) ? myVar : myOtherVar;', output: 'const myExpression = myVar ?? myOtherVar;', parserOptions: {ecmaVersion: 2020}},
{code: '!isNil(myVar) ? myVar : myOtherVar;', output: 'myVar ?? myOtherVar;', parserOptions: {ecmaVersion: 2020}}
].map(withDefaultPragma).map(toErrorObject)
})