2018-10-12 10:42:18 -07:00
|
|
|
import { CompiledRules } from 'nearley';
|
|
|
|
import nearley from 'nearley';
|
|
|
|
import { Parser } from 'wherehows-web/typings/modules/nearley';
|
|
|
|
|
|
|
|
/**
|
2019-08-31 20:51:14 -07:00
|
|
|
* We will pre-process the string to remove extra spaces that will slow down the parser.
|
2018-10-12 10:42:18 -07:00
|
|
|
* @param text
|
|
|
|
* @param grammar
|
|
|
|
*/
|
|
|
|
export const parse = (text: string, grammar: CompiledRules): Parser => {
|
|
|
|
const noExtraSpaces = text.replace(/[\s]+/gi, ' ').trim();
|
|
|
|
const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
|
2019-08-31 20:51:14 -07:00
|
|
|
const withLastSpace = text.endsWith(' ') ? `${noExtraSpaces} ` : noExtraSpaces;
|
|
|
|
parser.feed(withLastSpace);
|
2018-10-12 10:42:18 -07:00
|
|
|
return parser;
|
|
|
|
};
|