1

I have written the code to parse the following expression

=name1 OR <=name2

to

{
    operator: 'or',
    values: [
        {
            op: '=',
            value: 'name1 ',
        },
        {
            op: '<=',
            value: 'name2',
        },
    ],
}

using PEG.js. Please check the code sandbox.

But I am not getting how to parse the follwong expression

=name1 OR =name2 OR =name3 OR =name4

It should return the following structured object

{
    operator: 'or',
    values: [
        {
            op: '=',
            value: 'name1',
        },
        {
            op: '=',
            value: 'name2',
        },
        {
            op: '=',
            value: 'name3',
        },
        {
            op: '=',
            value: 'name4',
        }
    ],
}

code sandbox:https://codesandbox.io/s/javascript-testing-sandbox-forked-76n0p?file=/src/index.js

Benk I
  • 185
  • 13

1 Answers1

2

I guess you can describe your language with the following grammar:

Expression = head:Term tail:(_ "OR" _ Term _)*  {
    return [head].concat(tail.map(t => t[3]))
}

Term = _ op:Operator _ name:Name  {
    return {op, name}
}

Operator = "=" / "=<"

Name = head:[a-z] tail:([a-z0-9]*) {
    return head + tail.join('')
}

_ = [ \t\n\r]*

You can try it online on https://pegjs.org/online

georg
  • 211,518
  • 52
  • 313
  • 390
  • Thanks for the solution. This is the first time I am using `PEG.js` and I want to run it in a code sandbox only (I want to share the code with my project mate). So please, can you guide me to put your solution in the sandbox because when I used the given solution, it showed an error in the sandbox but worked correctly in https://pegjs.org/online. Thanks:) – Benk I Aug 13 '21 at 09:27
  • @BenkI: see here https://stackoverflow.com/a/68770803/989121 – georg Aug 13 '21 at 10:37
  • Georg, if you have some time please check this once https://stackoverflow.com/questions/68799056/parse-expression-with-javascript-using-peg Thanks :) – Benk I Aug 16 '21 at 08:01