Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 35 additions & 24 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,41 @@
'use strict';

module.exports = TokenStream;
function TokenStream(tokens) {
if (!Array.isArray(tokens)) {
throw new TypeError('tokens must be passed to TokenStream as an array.');
/** @template T */
module.exports = class TokenStream {
#tokens

/** @param {T[]} tokens */
constructor (tokens) {
if (!Array.isArray(tokens)) {
throw new TypeError('tokens must be passed to TokenStream as an array.');
}
this.#tokens = tokens;
}
this._tokens = tokens;
}
TokenStream.prototype.lookahead = function (index) {
if (this._tokens.length <= index) {
throw new Error('Cannot read past the end of a stream');

/** @param {number} index */
lookahead (index) {
if (this.#tokens.length <= index) {
throw new Error('Cannot read past the end of a stream');
}
return this.#tokens[index];
}

peek () {
if (this.#tokens.length === 0) {
throw new Error('Cannot read past the end of a stream');
}
return this.#tokens[0];
}
return this._tokens[index];
};
TokenStream.prototype.peek = function () {
if (this._tokens.length === 0) {
throw new Error('Cannot read past the end of a stream');

advance () {
if (this.#tokens.length === 0) {
throw new Error('Cannot read past the end of a stream');
}
return this.#tokens.shift();
}
return this._tokens[0];
};
TokenStream.prototype.advance = function () {
if (this._tokens.length === 0) {
throw new Error('Cannot read past the end of a stream');

/** @param {T} token */
defer (token) {
this.#tokens.unshift(token);
}
return this._tokens.shift();
};
TokenStream.prototype.defer = function (token) {
this._tokens.unshift(token);
};
}
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
"description": "Take an array of token and produce a more useful API to give to a parser",
"dependencies": {},
"devDependencies": {
"istanbul": "*"
"c8": "*"
},
"scripts": {
"test": "node test && npm run coverage",
"coverage": "istanbul cover test"
"test": "node test/index.js && npm run coverage",
"coverage": "c8 node test/index.js"
},
"repository": {
"type": "git",
Expand Down
2 changes: 1 addition & 1 deletion test/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

var assert = require('assert');
var TokenStream = require('../');
var TokenStream = require('../index.js');

assert.throws(function () {
new TokenStream('foo,bar');
Expand Down