TS-Lexer
A simple Lexer written in TypeScript
API
Lexer
Create a Lexer.
Params
input
{String} (Optional): Pass an input string.
// es5const Lexer = ;const lexer = ;// Optional `input` parameter.const input = 'some input string';const lexer = input;
setInput()
Params
input
{String} : Pass an input string.
const input = 'a string';lexer;console; // 'a string'
addRule()
Add a rule to the Lexer.
Params
type
{String}pattern
{RegExp}fn
{Function} (Optional)
// Examplelexer;// With optional `fn` passedlexer;
addRules()
Add an array of rules to the Lexer.
Params
rules
{Array}
// Exampleconst rulesArr =type: 'newline'regex: /\n/type: 'digit'regex: /\d/return lexeme;lexer;
consume()
Consume the given length of the input string.
Params
length
{Number}
// Examplelexer;lexer;console; // 'e string'console; // 'som'
match()
Match the string with the passed RegExp pattern.
Params
regex
{RegExp}
// Examplelexer;lexer; // ["som", index: 0, input: "some string", groups: undefined]
scan()
Scan the Lexer's input and return an array of tokens.
// Exampleconst rulesArr =type: 'two_digit_number'regex: /^[0-9]{2}/type: 'four_letter_word'regex: /^[a-zA-Z]{4}/// Set Lexer ruleslexer// Set Lexer inputlexer;lexer // [{length: 2, type: 'two_digit_number', value: 24}, {length: 4, type: four_letter_word, value: 'some'}]