Created
February 6, 2012 19:38
-
-
Save asawilliams/1754313 to your computer and use it in GitHub Desktop.
Find all the occurrences of every string in a JS file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var analyze = function() { | |
var scriptData, | |
strings, | |
occurances; | |
/* | |
* Analyze a single script to determine | |
* how often a string is used. | |
* s: html script object. | |
*/ | |
function script(s) { | |
// reset | |
scriptData = null; | |
strings = []; | |
occurances = {}; | |
getScripts(s); | |
} | |
function getScripts(s) { | |
$.get(s.src, function(data) { | |
scriptData = data; | |
getStrings(); | |
determineOccurances(); | |
sortOccurances(); | |
displayResults(); | |
}); | |
} | |
function getStrings() { | |
strings = scriptData.match(/((?:'|")([a-zA-Z0-9 _.#-]+)(?:'|"))+/g); | |
} | |
function determineOccurances() { | |
var len = strings.length; | |
for(var i=0; i < len; i++) { | |
if(typeof occurances[strings[i]] === 'undefined') { | |
occurances[strings[i]] = 1; | |
} else { | |
occurances[strings[i]] += 1; | |
} | |
} | |
} | |
function sortOccurances() { | |
var sorted = []; | |
for (var key in occurances) { | |
sorted.push({string: key, value: occurances[key]}); | |
} | |
occurances = sorted; | |
occurances.sort(function(a, b) { | |
return a.value-b.value; | |
}); | |
} | |
function displayResults() { | |
var len = occurances.length; | |
for (var i=0; i < len; i++) { | |
console.log(occurances[i].string+': '+occurances[i].value); | |
} | |
} | |
return { | |
script: script, | |
}; | |
}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment