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");
}
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.
Interesting question. I too question the motive behind it... Hopefully it's just for debugging or understanding the structure of the application better.
If you could tie into each function, you can get the callee by:
arguments.callee.name
And write that to a global variable (perhaps an object with each key being the name of the function, and the value being an array of function names).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With