switch-new-expression-to-call-expression.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. const isNewExpressionWithParentheses = require('../utils/is-new-expression-with-parentheses.js');
  3. const {isParenthesized} = require('../utils/parentheses.js');
  4. function * fixReturnStatementArgument(newExpression, sourceCode, fixer) {
  5. const {parent} = newExpression;
  6. if (
  7. parent.type !== 'ReturnStatement'
  8. || parent.argument !== newExpression
  9. || isParenthesized(newExpression, sourceCode)
  10. ) {
  11. return;
  12. }
  13. const returnStatement = parent;
  14. const returnToken = sourceCode.getFirstToken(returnStatement);
  15. const classNode = newExpression.callee;
  16. // Ideally, we should use first parenthesis of the `callee`, and should check spaces after the `new` token
  17. // But adding extra parentheses is harmless, no need to be too complicated
  18. if (returnToken.loc.start.line === classNode.loc.start.line) {
  19. return;
  20. }
  21. yield fixer.insertTextAfter(returnToken, ' (');
  22. yield fixer.insertTextAfter(newExpression, ')');
  23. }
  24. function * switchNewExpressionToCallExpression(node, sourceCode, fixer) {
  25. const [start] = node.range;
  26. let end = start + 3; // `3` = length of `new`
  27. const textAfter = sourceCode.text.slice(end);
  28. const [leadingSpaces] = textAfter.match(/^\s*/);
  29. end += leadingSpaces.length;
  30. yield fixer.removeRange([start, end]);
  31. if (!isNewExpressionWithParentheses(node, sourceCode)) {
  32. yield fixer.insertTextAfter(node, '()');
  33. }
  34. /*
  35. Remove `new` from this code will makes the function return `undefined`
  36. ```js
  37. () => {
  38. return new // comment
  39. Foo()
  40. }
  41. ```
  42. */
  43. yield * fixReturnStatementArgument(node, sourceCode, fixer);
  44. }
  45. module.exports = switchNewExpressionToCallExpression;