Search code examples
javascriptdependency-graph

Get a list of all functions that are called by another function


In JavaScript, is it possible to obtain a list of all functions that are called by another function? I want to create a tree of function dependencies, to analyze how the functions in a script are related to each other (and which functions are required by which other functions).

For example:

getAllCalledFunctions(funcA); //this should return [funcB, funcC, funcD], since these are the functions that are required by funcA.

function getAllCalledFunctions(functionName){
    //how should I implement this?
}

function funcA(){
    funcB();
    funcC();
}

function funcB(){
    funcD();
}

function funcC(){
    funcD();
}

function funcD(){
    console.log("This function is called by funcC and funcD");
}

Solution

  • Esprima may help you. It is a Javascript parser that can help you do static code analysis.

    Here's a quick example (http://jsfiddle.net/fyBvT/):

    var code = 'function funcA() { funcB(); funcC(); } function funcB(){ funcD(); } function funcC() { funcD(); } function funcD(){ console.log("This function is called by funcC and funcD"); }';
    var syntax = esprima.parse(code);
    
    var funcs = [];
    _.each(syntax.body, function(i) {
        if (i.type == 'FunctionDeclaration') {
            var func = {name: i.id.name};
    
            _.each(i.body.body, function(j) {
                if (j.type == 'ExpressionStatement' && j.expression.type == 'CallExpression') {
                    func.calls = func.calls || [];
                    func.calls.push(j.expression.callee.name);
                }
            });
    
            funcs.push(func);
        }
    });
    
    console.log(funcs);
    

    Clearly this needs a lot of help to offer much value, but it might give you some idea of what's possible and where to start.