I want to implement a meta-circular evaluator in JS with support to functional programming.
How can I parse this?
[1..10]
I want to receive 1 and 10
I want to implement a meta-circular evaluator in JS with support to functional programming.
How can I parse this?
[1..10]
I want to receive 1 and 10
This is a basic implementation of generating a range.
The goal you are talking about is going to be too complex for regex (firmly tongue in cheek).
Using tagged template literal syntax.
Regex finds two digit sequences, converts to numbers. Fills an array.
range = (str,...args) =>
(([,min,max])=>
Array(Math.abs(max-min)+1).fill(+min).map((_,i)=>_+i*(min>max?-1:1)))
((Array.isArray(str) ? str.map((s,i)=>s+args[i]).join('') : str)
.match(/\[\s*(-?\d+)\s*\.\.\s*(-?\d+)\s*\]/))
x=-3, y=0
console.log(
range`[5..1]`,
range`[1..10]`,
range("[ 5 .. -2 ]"),
range`[${x}.. ${y}]`
)
Regex: \[([0-9]+)\.\.([0-9]+)\]
I confirmed the regex via regex101.com and let it generate the sample code.
const regex = /\[([0-9]+)\.\.([0-9]+)\]/gm;
const str = `[1..10]`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Result:
Found match, group 0: 1..10
Found match, group 1: 1
Found match, group 2: 10
I've been longing to try out nearley.js for so long. This may or may not be what you wanted!
Please do note that I have assumed that what you want to get out of
[1..10]
is all the numbers from1
to10
(included), e.g.[1,2,3,4,5,6,7,8,9,10]
.Let's define the grammar for this mini language
grammar.ne
What I like about nearley.js is that it allows you to embed post processors for your rules right into the grammar. It may looks ugly but I find it pretty neat actually!
Another cool thing, is that nearley.js comes with a suite of useful tools. One of them generates a diagram for your grammar:
Here's the output:
As you can see a range is a sequence of:
"["
".."
"]"
Now we need to compile that grammar
This code needs to be loaded into a parser. I'm just showing the compiled grammar for illustration purpose:
grammar.js
Now let's build a parser and use it!
index.js