backward-token-cursor.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @fileoverview Define the cursor which iterates tokens only 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 only in reverse.
  16. */
  17. module.exports = class BackwardTokenCursor 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.index = utils.getLastIndex(tokens, indexMap, endLoc);
  30. this.indexEnd = utils.getFirstIndex(tokens, indexMap, startLoc);
  31. }
  32. /** @inheritdoc */
  33. moveNext() {
  34. if (this.index >= this.indexEnd) {
  35. this.current = this.tokens[this.index];
  36. this.index -= 1;
  37. return true;
  38. }
  39. return false;
  40. }
  41. /*
  42. *
  43. * Shorthand for performance.
  44. *
  45. */
  46. /** @inheritdoc */
  47. getOneToken() {
  48. return (this.index >= this.indexEnd) ? this.tokens[this.index] : null;
  49. }
  50. };