30 Jul 08 Removing duplicate functions from a (javascript) source file
The impetus for this solution was to eliminate the duplication of functions a javascript source file. The concepts could be applied with little modification to any language with c-like syntax. I chose to implement in PHP because that's what I happen to be working with these days though I do make use of a grep trick which means it would be easiest to run this on some type of posix system with grep & php.
A project I've been working on had a vexing issue of a bunch of duplicate function declarations in one of its source files. My guess is it is attributed to pasting the content of the file. Unfortunately, the file had undergone many changes since the issue was first discovered. If a function was updated that had two copies of it, either the top or bottom block would have the other declaration manually removed. This made it impossible to just remove a single chunk representing the first or second set of changes because that could potentially remove a vital function breaking the whole app!
So without further ado:
$file = "source.js"; $grep = system("grep -hEo \"^\s*function \w+\" $file | sort | uniq -d"); $functions = split("\n", $grep); // I'd recommend taking a look at the functions to ensure $functions seems consistent with your data & goals $blob = file_get_contents(); foreach ($functions as $function) { $start = strpos($javascript, $function); // loop through each char until we get to the close bracket $stack = array(); for ($i = $start, $j = strlen($javascript); $i < $j; ++$i) { $letter = substr($javascript, $i, 1); if ($letter == "{") { $stack[] = "true"; } elseif ($letter == "}") { array_shift($stack); if (count($stack) == 0) { $lastBracket = $i+1; break; } } } //echo substr($javascript, $start, ($lastBracket - $start)) . "\n"; $javascript = substr($javascript, 0, $start) . substr($javascript, $lastBracket); } echo $javascript;




The impetus for this solution was to eliminate the duplication of functions a javascript source file…..
А вы сами поняли?…