TotalTechGeek / json-logic-engine

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

Expand the get method, add support for 'var' in the second parameter #21

Closed tatarysh closed 10 months ago

tatarysh commented 10 months ago

Description: Currently, the get functionality works correctly, but in cases where the second parameter is provided as a string, I need to use other logical blocks as well.

test('get operator w/ object key as string', async () => {
  const f = await logic.build({ get: [{ var: 'selected' }, 'b'] })

  expect(await f({
    selected: {
      b: 2
    }
  })).toEqual(2)
})

test('get operator w/ object key as var', async () => {
  const f = await logic.build({ get: [{ var: 'selected' }, { var: 'key' }] })

  expect(await f({
    selected: {
      b: 2
    },
    key: 'b'
  })).toEqual(2)
})
✓ get operator w/ object key as string (3 ms)
✕ get operator w/ object key as var (1 ms)

I have attempted to modify the get method to include additional conditions in the second parameter, but due to its complexity, I have not been successful. This enhancement would provide more flexibility and allow for the use of various logical blocks in the second parameter.

In my use case, I have an object where the keys represent variant IDs, and the values represent the selected variants. During page rendering, I need to dynamically determine which variant is selected to obtain a true or false value. Therefore, it's crucial for the second parameter of the get method to accept a variable rather than a static value.

Additionally, I believe that some methods can be optimized. For example, the defaultValue, key or obj variables are declared (in get method) but only used when data is an array; otherwise, it is unnecessary. If you don't mind, I can work on this in my free time.

TotalTechGeek commented 10 months ago

Hey @tatarysh, excellent find.

I went ahead and resolved the immediate issue of dynamic keys not being possible in the compiled version of the get function (especially since some of the code is indeed a bit convoluted), and published a new version.

For dynamic keys, I've set it up to not attempt to not optimize it via code injection, as I don't think it'll yield significant gains. Meanwhile, static keys will continue to be optimized in advance.

If you don't mind, I can work on this in my free time.

I definitely do not mind!