Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda