Skip to content

Instantly share code, notes, and snippets.

@cy6erlion
Last active May 15, 2020 18:36
Show Gist options
  • Save cy6erlion/35b29f83f07dedcdcabde4e78e908fb8 to your computer and use it in GitHub Desktop.
Save cy6erlion/35b29f83f07dedcdcabde4e78e908fb8 to your computer and use it in GitHub Desktop.
Javascript Letter Frequency Analyzer.
// Takes an array of characters or a string
function analyze(input){
var chars = undefined;
var obj = {};
if(input instanceof Array){
chars = input;
} else if(typeof input === 'string' || input instanceof String) {
chars = input.split("");
} else return null;
for(var i = 0; i < chars.length; i++) {
if(!obj[chars[i]]) obj[chars[i]] = {frequency: 1};
else obj[chars[i]].frequency = obj[chars[i]].frequency + 1;
}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
obj[key].percentage = (obj[key].frequency / chars.length) * 100;
}
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment