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.

18
  • What's the difference between anon and g? Couldn't expand(fn) just return fn? Commented May 24, 2016 at 23:36
  • 4
    That sounds like you want to modify source code at runtime. That's not really possible, unless you want to use a JS parser, to some AST transformation, print the AST and eval the result. Commented May 24, 2016 at 23:40
  • 3
    @EmrehanTuzun why would want to do this? anon does the same thing as g Commented May 24, 2016 at 23:40
  • 1
    Well, it already exists ;) (kind of) babeljs.io But usually this is done as a compile step, not at runtime. This will also easily break if f in your example was a closure. Commented May 24, 2016 at 23:48
  • 1
    @EmrehanTuzun easier to include the library in the foreign sandbox Commented May 24, 2016 at 23:50

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.