3

I need a function expand(fn), that will accept any function and return a function where all the function calls in the input function are replaced with codes of these functions.

For example, given f and g functions below:

function f(x) {
    console.log('f: ' + x);
}

function g(x) {
    console.log('g: ' + x);
    f(x + 1);
}

expand(g) should return such a function:

function anon(x) {
    console.log('g: ' + x);
    var arg1 = x + 1;
    {
        console.log('f: ' + arg1);
    }
}

expand(g) should work just as the function g. But expand(g) should not call any functions except standard JavaScript functions.

Such an expand function would be handy when I'm going to pass just a plain JavaScript function to a foreign sandbox and I want to be able to use my functions and other JS libraries in that function to be executed there.

I'd like to be able to expand functions with parameters, functions from external libraries and nested functions. Even recursive functions could be converted to loops but I'm not looking for that for now.

Han Tuzun
  • 461
  • 1
  • 5
  • 9

0 Answers0