UNPKG

relative-time-expression

Version:
89 lines (88 loc) 2.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var error_1 = require("./error"); var wsRegexp = /^\s+/; var unitRegexp = /^[smhdwMy]/; var intRegexp = /^[0-9]+/; var opRegexp = /^[+-/\\]/; var nowRegexp = /now/i; var Tokenizer = /** @class */ (function () { function Tokenizer(raw) { this.raw = raw; this.tokens = []; this.iter = 0; } Tokenizer.parse = function (exp) { return new Tokenizer(exp).parse(); }; Tokenizer.prototype.parse = function () { while (this.iter < this.raw.length) { this.tokens.push(this.nextToken()); } return this.tokens; }; Tokenizer.prototype.nextToken = function () { var nextChar = this.raw.charAt(this.iter); if (wsRegexp.test(nextChar)) { return this.readWs(); } else if (unitRegexp.test(nextChar)) { return this.readUnit(); } else if (intRegexp.test(nextChar)) { return this.readInt(); } else if (opRegexp.test(nextChar)) { return this.readOp(); } else if (nowRegexp.test(this.raw.slice(this.iter, this.iter + 3))) { return this.readNow(); } throw error_1.createError({ actual: nextChar, start: this.iter, end: this.iter + 1, }); }; Tokenizer.prototype.readNow = function () { return this.readSize('keyword', 3); }; Tokenizer.prototype.readWs = function () { return this.readWhile('ws', function (c) { return wsRegexp.test(c); }); }; Tokenizer.prototype.readUnit = function () { return this.readSize('unit'); }; Tokenizer.prototype.readInt = function () { return this.readWhile('number', function (c) { return intRegexp.test(c); }); }; Tokenizer.prototype.readOp = function () { return this.readSize('op'); }; Tokenizer.prototype.readSize = function (type, size) { if (size === void 0) { size = 1; } var raw = this.raw.slice(this.iter, this.iter + size); this.iter += size; return { type: type, raw: raw, start: this.iter - size, end: this.iter, }; }; Tokenizer.prototype.readWhile = function (type, cb) { var start = this.iter++; while (cb(this.raw.charAt(this.iter))) { this.iter++; } var raw = this.raw.slice(start, this.iter); return { type: type, raw: raw, start: start, end: this.iter, }; }; return Tokenizer; }()); exports.default = Tokenizer;