index.js 841 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. module.exports = TokenStream;
  3. function TokenStream(tokens) {
  4. if (!Array.isArray(tokens)) {
  5. throw new TypeError('tokens must be passed to TokenStream as an array.');
  6. }
  7. this._tokens = tokens;
  8. }
  9. TokenStream.prototype.lookahead = function (index) {
  10. if (this._tokens.length <= index) {
  11. throw new Error('Cannot read past the end of a stream');
  12. }
  13. return this._tokens[index];
  14. };
  15. TokenStream.prototype.peek = function () {
  16. if (this._tokens.length === 0) {
  17. throw new Error('Cannot read past the end of a stream');
  18. }
  19. return this._tokens[0];
  20. };
  21. TokenStream.prototype.advance = function () {
  22. if (this._tokens.length === 0) {
  23. throw new Error('Cannot read past the end of a stream');
  24. }
  25. return this._tokens.shift();
  26. };
  27. TokenStream.prototype.defer = function (token) {
  28. this._tokens.unshift(token);
  29. };