backward-token-comment-cursor.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @fileoverview Define the cursor which iterates tokens and comments in reverse.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const Cursor = require("./cursor");
  10. const utils = require("./utils");
  11. //------------------------------------------------------------------------------
  12. // Exports
  13. //------------------------------------------------------------------------------
  14. /**
  15. * The cursor which iterates tokens and comments in reverse.
  16. */
  17. module.exports = class BackwardTokenCommentCursor extends Cursor {
  18. /**
  19. * Initializes this cursor.
  20. * @param {Token[]} tokens The array of tokens.
  21. * @param {Comment[]} comments The array of comments.
  22. * @param {Object} indexMap The map from locations to indices in `tokens`.
  23. * @param {number} startLoc The start location of the iteration range.
  24. * @param {number} endLoc The end location of the iteration range.
  25. */
  26. constructor(tokens, comments, indexMap, startLoc, endLoc) {
  27. super();
  28. this.tokens = tokens;
  29. this.comments = comments;
  30. this.tokenIndex = utils.getLastIndex(tokens, indexMap, endLoc);
  31. this.commentIndex = utils.search(comments, endLoc) - 1;
  32. this.border = startLoc;
  33. }
  34. /** @inheritdoc */
  35. moveNext() {
  36. const token = (this.tokenIndex >= 0) ? this.tokens[this.tokenIndex] : null;
  37. const comment = (this.commentIndex >= 0) ? this.comments[this.commentIndex] : null;
  38. if (token && (!comment || token.range[1] > comment.range[1])) {
  39. this.current = token;
  40. this.tokenIndex -= 1;
  41. } else if (comment) {
  42. this.current = comment;
  43. this.commentIndex -= 1;
  44. } else {
  45. this.current = null;
  46. }
  47. return Boolean(this.current) && (this.border === -1 || this.current.range[0] >= this.border);
  48. }
  49. };