Logical Operators
Learn methods that simulate logical operators which are used to parse sentences.
We'll cover the following...
The NOT operator
In this lesson, we’ll try to simulate the NOT operator in the parsing process. This operator can be useful when we need to analyze portions from the input string different from some predefined string values. We need to implement a method that takes an array of strings as a parameter and returns a function that takes the input string and the cursor. Below is the implementation of the method.
Note: We can enter any string value as an input at the bottom of the widget to run the code.
import { AST, NotAsExpected } from "./util";import { run } from "./stdin";/*** A function to simulate the not operator.** @param {Array} strings Input strings.* @return {function} A function that takes the input string to parse.*/function not(strings) {/*** @param {string} input Input string.* @param {int} cursor A point from where to start parsing.* @return {object} An abstract syntax tree.*/return (input, cursor) => {if (cursor < input.length) {for (let i = 0; i < strings.length; i++) {const string = strings[i];if (input.slice(cursor, cursor + string.length) === string) {return new NotAsExpected(`not "${string}"`, cursor);}}return new AST(input[cursor], cursor + 1);} else {return new NotAsExpected(`not ${strings.map(JSON.stringify).join(", ")}`, cursor);}};}/* Begin main */run(not(["span", "div", "p"]));
Enter the input below
If we look at the body of the not
method, we can see that a first check on the length of the input string is necessary. If it’s greater than the cursor, we should a ...