Skip to content

Instantly share code, notes, and snippets.

@oranj
Created July 10, 2012 15:57
Show Gist options
  • Save oranj/3084307 to your computer and use it in GitHub Desktop.
Save oranj/3084307 to your computer and use it in GitHub Desktop.
Javascript Function Pruner
<?php
if (count($argv) < 2) {
die("Please enter a filename");
}
$filename = $argv[1];
$funcNameRegex = '(?P<func>[a-zA-Z0-9_$]+)';
$contents = file_get_contents($filename);
if (! $contents) {
die("No data for file \"$filename\"");
}
$funcNameRegexes = Array(
'/[\'"]?'.$funcNameRegex.'[\'"]\s*:\s*function/i',
'/function\s+'.$funcNameRegex.'\s*\(/i',
'/var\s+'.$funcNameRegex.'\s*=\s*function/i'
);
$nameLocations = array();
$useLocations = array();
foreach ($funcNameRegexes as $regex) {
if (preg_match_all($regex, $contents, $output, PREG_OFFSET_CAPTURE)) {
foreach ($output['func'] as $out) {
$nameLocations[$out[0]] []= $out[1];
}
}
}
$funcUseRegexes = Array(
'/that\.'.$funcNameRegex.'\(/i',
'/this\.'.$funcNameRegex.'\(/i',
'/\b'.$funcNameRegex.'\(/i',
'/[\(,]\s*'.$funcNameRegex.'\s*[\),]/i'
);
foreach ($funcUseRegexes as $regex) {
if (preg_match_all($regex, $contents, $output, PREG_OFFSET_CAPTURE)) {
foreach ($output['func'] as $out) {
$useLocations[$out[0]] []= $out[1];
}
}
}
$output = array();
$notUsed = array();
foreach ($nameLocations as $name => $defined) {
$output [$name] = array(
'defined' => $defined,
'used' => array()
);
if (! isset($useLocations[$name])) {
$notUsed [$name] = $defined;
} else {
$output[$name]['used'] = $useLocations[$name];
}
}
foreach ($notUsed as $name => $defined_locations) {
echo "\033[44m\033[1;37m function $name \033[0m\n";
echo " Defined at\n - line ";
echo join("\n - line ", $defined_locations);
echo "\n";
}
@oranj
Copy link
Author

oranj commented Jul 10, 2012

This script will detect unused functions within a single javascript file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment