Question:
Create a function that convert a dynamic Json to a formula in Typescript

You can Create a function to convert a dynamic Json to a formula in Typescript using the below written code: 



function compile(obj, op) {

    if (obj.regolaPerCollegamento)

        return obj.regolaPerCollegamento.map(p => JSON.stringify(p)).join(op)


    let res = []


    for (let [op, val] of Object.entries(obj)) {

        if (op === 'and')

            res.push(compile(val, ' && '))

        if (op === 'or')

            res.push(compile(val, ' || '))

        if (op === 'not')

            res.push('not ' + compile(val, ' '))

    }


    if (res.length === 1)

        return res[0]


    return '(' + res.join(op) + ')'

}


//


let json = {

    "or": {

        "and": {

            "regolaPerCollegamento": [

                {

                    "tipoCollegamentoEsistente": 115,

                    "quantita": "NESSUNO"

                },

                {

                    "tipoCollegamentoEsistente": 118,

                    "quantita": "NESSUNO"

                }

            ]

        },

        "or": {

            "regolaPerCollegamento": [

                {

                    "tipoCollegamento": 115,

                    "minimo": 1

                },

                {

                    "tipoCollegamento": 118,

                    "minimo": 1

                }

            ]

        }

    }

}


b = compile(json, ' ')

console.log(b)


That being said, this is a weird way to represent an AST, you might be better off with a structure like this:


interface Rule { 

whatever

}


interface Node

{

    op: string

    args: Array <Node | Rule>

}


//


let ast = {

    op: 'or',

    args: [

        {

            op: 'and',

            args: [

                { "tipoCollegamentoEsistente": 115, "quantita": "NESSUNO" },

                { "tipoCollegamentoEsistente": 118, "quantita": "NESSUNO" }

            ]

        },

        {

            op: 'or',

            args: [

                { "tipoCollegamento": 115, "minimo": 1 },

                { "tipoCollegamento": 118, "minimo": 1 }

            ]

        }

    ]

}


Suggested blogs:

>How to Select checkboxes on an HTML treeview with JavaScript?

>How to use querySelectorAll()" with multiple conditions in JavaScript?

>How to fix mouseover event glitch in JavaScript?

>How to do light and dark mode in a website using HTML and JavaScript?

>How to manipulate manipulating Array object in JavaScript?

>How to merge an object into Array with the same key in JavaScript?

>Javascript Error Solved: Property 'id' does not exist on type 'T'

>Why highlighted table row using class not working in JavaScript?

>How to rename an object key based on the condition in JavaScript?

>How to sort an array based on another array in Javascript?

>Javascript: Modal not closing with a button


Nisha Patel

Nisha Patel

Submit
0 Answers