Skip to content

Instantly share code, notes, and snippets.

@kunalbhatt
Forked from troyleach/gist:e96ffebcc9498e71ea5d
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save kunalbhatt/b6fcf4f2e9040b371312 to your computer and use it in GitHub Desktop.

Select an option

Save kunalbhatt/b6fcf4f2e9040b371312 to your computer and use it in GitHub Desktop.
// Write a function charFreq() that takes a string and builds a frequency listing of the characters contained in it.
// Represent the frequency listing as a Javascript object.
// Try it with something like charFreq("abbabcbdbabdbdbabababcbcbab").
// I got a lot help from stack on this one. I had no idea how to make a object from a string.
// and in doing research for that I found a solution to something similar to this. But I do understand
// how every line of code works and why!
function charFreq(source) {
var frequency = {};
for (var i = 0; i < source.length; i++) {
var character = source.charAt(i); //KUNAL: Why do you use charAt vs source[i]
if (frequency[character]) { //KUNAL: What about case sensitive letters?
frequency[character]++;
} else {
frequency[character] = 1;
}
}
return frequency;
};
console.log(charFreq("aabbabcbdbabdbdbabababcbcbab"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment