negative-index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const isSameReference = require('../utils/is-same-reference.js');
  3. const {getParenthesizedRange} = require('../utils/parentheses.js');
  4. const {isNumberLiteral} = require('../ast/index.js');
  5. const isLengthMemberExpression = node =>
  6. node.type === 'MemberExpression'
  7. && !node.computed
  8. && !node.optional
  9. && node.property.type === 'Identifier'
  10. && node.property.name === 'length';
  11. const isLiteralPositiveNumber = node =>
  12. isNumberLiteral(node)
  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. };