cshaa/filtrex

Get a list of used variables

Closed this issue · 1 comments

Hi!
Is there a way to get a list of used variables in the expression after compiling it.
E.g.
Expr: transactions <= 5 and abs(profit) > 20.5
Variables: ["transactions","profit"]

Thanks!

cshaa commented

Hey @irata73!
It should be quite easy to create a quick-and-dirty solution oneself using a custom prop function, as it is called every time the user tries to access a property. Something like this should work:

import { compileExpression } from "filtrex"

function getUsedVariables(expression, data) {
  const usedVars = []
  const options = {
    customProp: (varName, get, obj) => {
        if (obj === data) usedVars.push(varName)
        return get(varName)
    }
  }
  compileExpression(expression, options)(data)
  return usedVars
}

const data = { transactions: 10, profit: -3, weather: 'sunny' }

getUsedVariables('transactions <= 5 or abs(profit) > 20.5', data)
// [ "transactions", "profit" ]

Try this on Runkit.

The two big disadventages with this approach are:

  • If the user wants to access data that is not defined, you'll get an error.
  • It only lists the data that is actually accessed. Try replacing or with and in the expression and you'll only get ["transactions"] because of short-circuiting.

Both of these problems are solvable in Filtrex v3 (currently in pre-release) – there, you can change every function and every operator to evaluate its arguments/operands and then return an arbitrary value.

Alternatively, you might want to fork Filtrex and modify src/generateParser.js, so that it only cares about symbols.