Search code examples
javascriptregexparsingpegjs

Parse expression with JavaScript using PEG.js


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


Solution

  • 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