Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda