Search code examples
javascriptalgorithmuglifyjs

variable extraction from expression


I have below question and got no clue for it:

for expression in string: "func1( A+ func2(A)+ func3(B)+ C + 4 )" need a way to identify all variables, in this case are A , B, C. expression can be different so it should not be hard coded to just this pattern. for example: it could just be func1(A)+func2(B), and variables are A and B.

a little background: still take "func1( A+ func2(A)+ func3(B)+ C + 4 )" as an example, say I have other expressions for A : "A=sum(a)" and "B=sum(b)" and "C=sum(c)", I want to do a merge so that first expression becomes: "func1( sum(a)+ func2(sum(a))+ func3(sum(b))+ sum(c)+4)", in order to achieve this, I guess I need a way to identify all variables from the first expression, that's how the question comes.

Edit: just realized this is a little similar to a js minification process... just added uglifyjs tag to this question

any answers or clues are much appreciated!

Solved: This was solved with exprima.js which works with AST. Please check accepted answer and commnets


Solution

  • This should get you most of the way there. One problem I see you might have is that functions are also variables in JavaScript, so you'll have to pick out all of the variables (Identifiers) that aren't callees.

    $(function() {
      $('#out').text(
        JSON.stringify(
          esprima.parse("func1( A+ func2(A)+ func3(B)+ C + 4 )"),
          null, 2
        )
      );
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/jquery/esprima/2.7.1/esprima.js"></script>
    <pre id='out'>
    
    </pre>