Skip to content

Commit

Permalink
prefer-ternary: Refactor to use ESLint recommended way to extend fi…
Browse files Browse the repository at this point in the history
…x range (#857)
  • Loading branch information
fisker committed Dec 12, 2020
1 parent d0c4826 commit 90fc7b0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
14 changes: 6 additions & 8 deletions rules/prefer-ternary.js
@@ -1,9 +1,9 @@
'use strict';
const {isParenthesized} = require('eslint-utils');
const {flatten} = require('lodash');
const FixTracker = require('eslint/lib/rules/utils/fix-tracker');
const getDocumentationUrl = require('./utils/get-documentation-url');
const avoidCapture = require('./utils/avoid-capture');
const extendFixRange = require('./utils/extend-fix-range');

const messageId = 'prefer-ternary';

Expand Down Expand Up @@ -204,7 +204,7 @@ const create = context => {
context.report({
node,
messageId,
fix: fixer => {
* fix(fixer) {
const testText = getParenthesizedText(node.test);
const consequentText = typeof result.consequent === 'string' ?
result.consequent :
Expand Down Expand Up @@ -241,13 +241,11 @@ const create = context => {
}

const fixed = `${before}${testText} ? ${consequentText} : ${alternateText}${after}`;
if (!generateNewVariables) {
return fixer.replaceText(node, fixed);
}
yield fixer.replaceText(node, fixed);

return new FixTracker(fixer, sourceCode)
.retainRange(sourceCode.ast.range)
.replaceTextRange(node.range, fixed);
if (generateNewVariables) {
yield * extendFixRange(fixer, sourceCode.ast.range);
}
}
});
}
Expand Down
15 changes: 15 additions & 0 deletions rules/utils/extend-fix-range.js
@@ -0,0 +1,15 @@
'use strict';

/**
Extend fix range to prevent changes from other rules.
https://github.com/eslint/eslint/pull/13748/files#diff-c692f3fde09eda7c89f1802c908511a3fb59f5d207fe95eb009cb52e46a99e84R348
@param {ruleFixer} fixer - The fixer to fix.
@param {int[]} range - The extended range node.
*/
function * extendFixRange(fixer, range) {
yield fixer.insertTextBeforeRange(range, '');
yield fixer.insertTextAfterRange(range, '');
}

module.exports = extendFixRange;

0 comments on commit 90fc7b0

Please sign in to comment.