Question

Consider the following existing form in Javascript:

function foo(a,b,c) {
   // lots of stuff
}

A refactoring is needed on this code, such that each function of this form should end up like so:

['a', 'b', 'c', function foo(a,b,c) {
    // lots of stuff
}]

The prelude of the refactoring (the foo(a,b,c) part) is constant, so this is basically a search-and-replace job. But the hard part is finding the matching closing bracket of the function, and appending the closing square bracket to it. This is why standard search-replace in a standard text editor won't suffice. The function body is not constant.

What is the easiest way to run this refactoring on a large project with many instances of this pattern? Any reasonable tool or method is acceptable. (Command line or vim is best :))

[For anyone curious as to the scenario: the need is to make sure AngularJS injected functions are minification-safe by explicitly naming the injected parameters in the aforementioned structure]

Was it helpful?

Solution

esprima.org is a very nice JS-parser, that allows easy manipulation of code.

If you want something ready to use, then try: ngmin or ng-annotate.

OTHER TIPS

Ok, wrote some javascript to do that. I haven't tested it much, but it should work. performance is probably pretty bad though ;)

function refactor(code){
    var pos = 0;
    while(pos < code.length){
        console.log(pos);
        pos = code.indexOf('function foo(a,b,c)', pos);
        if(pos == -1) break;
        code = code.slice(0, pos) +  "['a', 'b', 'c', " + code.slice(pos);
        pos += 36;
        var counter = 1;
        while(counter > 0 && pos < code.length){
            var pos_next_open = code.indexOf('{', pos);
            var pos_next_close = code.indexOf('}', pos);
            if(pos_next_open > pos_next_close || pos_next_open == -1){
                --counter;
                pos = pos_next_close+1;
            } else {
                ++counter;
                pos = pos_next_open+1;
            }
        }
        code = code.slice(0, pos) +  "]" + code.slice(pos);
    }
    return code;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top