TotalTechGeek / json-logic-engine

Construct complex rules with JSON & process them.
MIT License
46 stars 9 forks source link

[Feature Request] Generate Logic From Input #4

Closed enchorb closed 1 year ago

enchorb commented 1 year ago

Hi,

Feel free to close this if not relevant or outside the scope of this library, but would it be possible given an input formula to return the json logic? Similar to libraries such as mr-parser?

Right now on the client facing side for generating a formula we essentially have building blocks of allowable functions/parameters which they can compose and we generate the logic with, but if this would be non-trivial to add then that would be great.

For Example:

engine.generateLogic('abs(-test+2000 / 20)')

/*
Would Return:
{
      abs: {
        '/': [
          {
            '+': [{ '*': [-1, { var: 'test' }] }, 2000]
          },
          20
        ]
      }
    }

*/
TotalTechGeek commented 1 year ago

Hi,

This is out of scope for the library, and I don't think I will support this inside of JSON Logic Engine, however, I actually do have something similar to what you're requesting in another library (that's not very documented right now) called "deejay-rxjs-dsl".

You can import the generateLogic function from it.

However, you'd need to prefix the variables with @.

Like: abs(-@.test+2000 / 20)

However, following the rules of PEMDAS, your expression there would parse to:

{
  abs: {
    '+': [
      {
        '-': {
          var: 'test'
        }
      },
      {
        '/': [
          2000,
          20
        ]
      }
    ]
  }
}

Because I assume you probably don't want to import the deejay library (it has other stuff built into it), I have compiled the Peggy grammar from the other repo for you, with the default starting rule being "Expression". There is a file in the attached document you could use in your project that has a parse function exported :P

expression-parser.js.zip

If you wish to compile the Peggy.js grammar yourself, you can grab the grammar spec from here: https://github.com/TotalTechGeek/deejay-rxjs-dsl/blob/main/parser/grammar.pegjs

And compile it yourself (turn caching on!). However, you'll need to set the startRule to Expression.

TotalTechGeek commented 1 year ago

Let me know if this helps :)

enchorb commented 1 year ago

Thanks a ton, tested for a variety of common inputs for use and it is working perfectly!