noMutableArray.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports["default"] = void 0;
  6. var _lodash = _interopRequireDefault(require("lodash"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  8. var schema = []; // const x = [];
  9. var isEmptyArrayLiteral = function isEmptyArrayLiteral(node) {
  10. return _lodash["default"].get(node, 'init.type') === 'ArrayExpression' && _lodash["default"].get(node, 'init.elements.length') === 0;
  11. }; // const x = new Array(); const y = Array();
  12. var isEmptyArrayInstance = function isEmptyArrayInstance(node) {
  13. if (_lodash["default"].get(node, 'init.type') === 'NewExpression' || _lodash["default"].get(node, 'init.type') === 'CallExpression') {
  14. return _lodash["default"].get(node, 'init.callee.name') === 'Array' && _lodash["default"].get(node, 'init.arguments.length') === 0;
  15. }
  16. return false;
  17. };
  18. var isAnnotationOfEmptyArrayInit = function isAnnotationOfEmptyArrayInit(node) {
  19. if (_lodash["default"].has(node, 'parent.parent.parent')) {
  20. var parent = _lodash["default"].get(node, 'parent.parent.parent');
  21. var isVariableDeclaration = _lodash["default"].get(parent, 'type') === 'VariableDeclarator';
  22. return isVariableDeclaration && (isEmptyArrayLiteral(parent) || isEmptyArrayInstance(parent));
  23. }
  24. return false;
  25. };
  26. var create = function create(context) {
  27. return {
  28. ArrayTypeAnnotation: function ArrayTypeAnnotation(node) {
  29. if (!isAnnotationOfEmptyArrayInit(node)) {
  30. context.report({
  31. fix: function fix(fixer) {
  32. var rawElementType = context.getSourceCode().getText(node.elementType);
  33. return fixer.replaceText(node, "$ReadOnlyArray<".concat(rawElementType, ">"));
  34. },
  35. message: 'Use "$ReadOnlyArray" instead of array shorthand notation',
  36. node: node
  37. });
  38. }
  39. },
  40. GenericTypeAnnotation: function GenericTypeAnnotation(node) {
  41. if (node.id.name === 'Array' && !isAnnotationOfEmptyArrayInit(node)) {
  42. context.report({
  43. fix: function fix(fixer) {
  44. return fixer.replaceText(node.id, '$ReadOnlyArray');
  45. },
  46. message: 'Use "$ReadOnlyArray" instead of "Array"',
  47. node: node
  48. });
  49. }
  50. }
  51. };
  52. };
  53. var _default = {
  54. create: create,
  55. meta: {
  56. fixable: 'code'
  57. },
  58. schema: schema
  59. };
  60. exports["default"] = _default;
  61. module.exports = exports.default;