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

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. const isNewExpressionWithParentheses = require('../utils/is-new-expression-with-parentheses.js');
  3. const {isParenthesized} = require('../utils/parentheses.js');
  4. const isOnSameLine = require('../utils/is-on-same-line.js');
  5. const addParenthesizesToReturnOrThrowExpression = require('./add-parenthesizes-to-return-or-throw-expression.js');
  6. const removeSpaceAfter = require('./remove-spaces-after.js');
  7. function * switchNewExpressionToCallExpression(newExpression, sourceCode, fixer) {
  8. const newToken = sourceCode.getFirstToken(newExpression);
  9. yield fixer.remove(newToken);
  10. yield removeSpaceAfter(newToken, sourceCode, fixer);
  11. if (!isNewExpressionWithParentheses(newExpression, sourceCode)) {
  12. yield fixer.insertTextAfter(newExpression, '()');
  13. }
  14. /*
  15. Remove `new` from this code will makes the function return `undefined`
  16. ```js
  17. () => {
  18. return new // comment
  19. Foo()
  20. }
  21. ```
  22. */
  23. if (!isOnSameLine(newToken, newExpression.callee) && !isParenthesized(newExpression, sourceCode)) {
  24. // Ideally, we should use first parenthesis of the `callee`, and should check spaces after the `new` token
  25. // But adding extra parentheses is harmless, no need to be too complicated
  26. yield * addParenthesizesToReturnOrThrowExpression(fixer, newExpression.parent, sourceCode);
  27. }
  28. }
  29. module.exports = switchNewExpressionToCallExpression;