negative-index.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const isSameReference = require('../utils/is-same-reference.js');
  3. const {getParenthesizedRange} = require('../utils/parentheses.js');
  4. const isLengthMemberExpression = node =>
  5. node.type === 'MemberExpression'
  6. && !node.computed
  7. && !node.optional
  8. && node.property.type === 'Identifier'
  9. && node.property.name === 'length';
  10. const isLiteralPositiveNumber = node =>
  11. node.type === 'Literal'
  12. && typeof node.value === 'number'
  13. && node.value > 0;
  14. function getNegativeIndexLengthNode(node, objectNode) {
  15. if (!node) {
  16. return;
  17. }
  18. const {type, operator, left, right} = node;
  19. if (type !== 'BinaryExpression' || operator !== '-' || !isLiteralPositiveNumber(right)) {
  20. return;
  21. }
  22. if (isLengthMemberExpression(left) && isSameReference(left.object, objectNode)) {
  23. return left;
  24. }
  25. // Nested BinaryExpression
  26. return getNegativeIndexLengthNode(left, objectNode);
  27. }
  28. function removeLengthNode(node, fixer, sourceCode) {
  29. const [start, end] = getParenthesizedRange(node, sourceCode);
  30. return fixer.removeRange([
  31. start,
  32. end + sourceCode.text.slice(end).match(/\S|$/).index,
  33. ]);
  34. }
  35. module.exports = {
  36. getNegativeIndexLengthNode,
  37. removeLengthNode,
  38. };