Last active
May 15, 2020 18:36
-
-
Save cy6erlion/35b29f83f07dedcdcabde4e78e908fb8 to your computer and use it in GitHub Desktop.
Javascript Letter Frequency Analyzer.
This file contains 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
// 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