Home Reference Source Repository

lib/token-types.js

// Thank you, http://stackoverflow.com/a/6969486
function toRegExp(str) {
    return new RegExp(str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'));
}
function normalize(regex) {
    if (typeof regex === 'string')
        regex = toRegExp(regex);
    if (!regex.source.startsWith('^'))
        return new RegExp(`^${regex.source}`, regex.flags);
    else
        return regex;
}
function first(arr, predicate) {
    let i = 0;
    for (const item of arr) {
        const result = predicate(item, i++);
        if (result)
            return { item, result };
    }
}
/**
 * @private
 */
export default class TokenTypes {
    constructor() {
        this.tokenTypes = [];
    }
    disable(type) {
        return this.enable(type, false);
    }
    enable(type, enabled = true) {
        this.tokenTypes
            .filter(t => t.type == type)
            .forEach(t => t.enabled = enabled);
        return this;
    }
    peek(source, position) {
        const s = source.substr(position);
        return first(this.tokenTypes.filter(tt => tt.enabled), tt => {
            tt.regex.lastIndex = 0;
            return tt.regex.exec(s);
        });
    }
    token(type, pattern, skip = false) {
        this.tokenTypes.push({
            type,
            regex: normalize(pattern),
            enabled: true,
            skip,
        });
        return this;
    }
}
//# sourceMappingURL=token-types.js.map