forked from sindresorhus/eslint-plugin-unicorn
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefer-nullish-coalescing.js
79 lines (71 loc) · 1.87 KB
/
prefer-nullish-coalescing.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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 = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer the nullish coalescing operator(`??`) over the logical OR operator(`||`).'
},
messages,
hasSuggestions: true
}
};