Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
How to implement array support with Chevrotain parser?

I am building a calculator with Chevrotain parser and I have played with their calculator example

Chevrotain Playground: https://chevrotain.io/playground/

Parser Grammar: Calculator embedded semantics

Input Sample: Parenthesis precedence

The example above uses integer as input/output. I would like to support integers AND arrays.

Basic example:

2 * ( 3 + 7 )

Example with arrays:

2 * ( {{array1}} + {{array2}} )

const map = {
  array1: [1, 2, 3, 4, 5],
  array2: [10, 20, 30, 40, 50]
}

I know how to lex and parse {{array}} but I don't know how to visit them or loop over the arrays to achieve the following result

2 * ( 1 + 10 ) = 22
2 * ( 2 + 20 ) = 44
2 * ( 3 + 30 ) = 66
2 * ( 4 + 40 ) = 88
2 * ( 5 + 50 ) = 110

End result of the parsing of 2 * ( {{array1}} + {{array2}} )

should be [22, 44, 66, 88, 110]

Once the AST has been created (including the arrays on some leaf node), how can I reduce it to the end result which is an array

One approach is to have some sort of state (with the current index) and run the visitor as many time as array.length. But it is unclear to me how to can be implemented with Chevretain

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This solution will work

const map = {
    array1: [1, 2, 3, 4, 5],
    array2: [10, 20, 30, 40, 50]
}

const { array1, array2 } = map;
const res = [];
for (let i = 0; i < (array1.length > array2.length ? array1.length : array2.length); i++) {
    if (array1[i] && array2[i]) {
        res.push((array1[i] + array2[i]) * 2);
    } else if (array1[i] && !array2[i]) {
        res.push(array1[i] * 2);
    } else {
        res.push(array1[i] * 2);
    }
}

// res = [ 22, 44, 66, 88, 110 ]

First, we will extract the arrays from an object, then we will create a loop that will run several times of the longer array (trinary operator). Inside the loop, we will insert the item from array1 plus the item from array2 doubled by 2 into the new array, and if there is no item in one of the spots in the arrays (meaning that one of the arrays is shorter than the other) we will insert only one item.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!