no-useless-fallback-in-spread.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const {matches} = require('./selectors/index.js');
  3. const {
  4. isParenthesized,
  5. getParenthesizedRange,
  6. } = require('./utils/parentheses.js');
  7. const {removeParentheses} = require('./fix/index.js');
  8. const shouldAddParenthesesToSpreadElementArgument = require('./utils/should-add-parentheses-to-spread-element-argument.js');
  9. const MESSAGE_ID = 'no-useless-fallback-in-spread';
  10. const messages = {
  11. [MESSAGE_ID]: 'The empty object is useless.',
  12. };
  13. const selector = [
  14. 'ObjectExpression',
  15. ' > ',
  16. 'SpreadElement.properties',
  17. ' > ',
  18. 'LogicalExpression.argument',
  19. matches([
  20. '[operator="||"]',
  21. '[operator="??"]',
  22. ]),
  23. ' > ',
  24. 'ObjectExpression[properties.length=0].right',
  25. ].join('');
  26. /** @param {import('eslint').Rule.RuleContext} context */
  27. const create = context => ({
  28. [selector](emptyObject) {
  29. return {
  30. node: emptyObject,
  31. messageId: MESSAGE_ID,
  32. /** @param {import('eslint').Rule.RuleFixer} fixer */
  33. * fix(fixer) {
  34. const sourceCode = context.getSourceCode();
  35. const logicalExpression = emptyObject.parent;
  36. const {left} = logicalExpression;
  37. const isLeftObjectParenthesized = isParenthesized(left, sourceCode);
  38. const [, start] = isLeftObjectParenthesized
  39. ? getParenthesizedRange(left, sourceCode)
  40. : left.range;
  41. const [, end] = logicalExpression.range;
  42. yield fixer.removeRange([start, end]);
  43. if (
  44. isLeftObjectParenthesized
  45. || !shouldAddParenthesesToSpreadElementArgument(left)
  46. ) {
  47. yield * removeParentheses(logicalExpression, fixer, sourceCode);
  48. }
  49. },
  50. };
  51. },
  52. });
  53. /** @type {import('eslint').Rule.RuleModule} */
  54. module.exports = {
  55. create,
  56. meta: {
  57. type: 'suggestion',
  58. docs: {
  59. description: 'Disallow useless fallback when spreading in object literals.',
  60. },
  61. fixable: 'code',
  62. messages,
  63. },
  64. };