I have a problem. I'm trying to create a function that return the number of letters of frequency of a particular string. Here is an example.
var a = letter_frequency("Hello");
a["H"] == 1; a["E"] == 1; a["L"] == 2; a["A"] == undefined;
Now I have the code I wrote but I don't know how to go forward. Can you help me?
function letter_frequency(s) {
if (s === undefined) {
return undefined;
} else {
var splitter = s.split()
}
}
Here one test
test( "Frequency", function() {
deepEqual(letter_frequency() , undefined);
var a = letter_frequency("Hello");
equal(a["H"] , 1, "For the String 'Hello' the number of 'H' chars should be 1");
equal(a["E"] , 1, "For the String 'Hello' the number of 'E' chars should be 1");
equal(a["L"] , 2, "For the String 'Hello' the number of 'L' chars should be 2");
equal(a["O"] , 1, "For the String 'Hello' the number of 'O' chars should be 1");
deepEqual(a["A"] , undefined, "For the String 'Hello' the number of 'A' chars should be undefined");
var a = letter_frequency("Software Atelier III");
equal(a["I"] , 4, "For the String 'Software Atelier III' the number of 'I' chars should be 4");
equal(a["S"] , 1, "For the String 'Software Atelier III' the number of 'S' chars should be 1");
equal(a["A"] , 2, "For the String 'Software Atelier III' the number of 'A' chars should be 2");
equal(a["O"] , 1, "For the String 'Software Atelier III' the number of 'O' chars should be 1");
equal(a["T"] , 2, "For the String 'Software Atelier III' the number of 'T' chars should be 2");
equal(a[" "] , 2, "For the String 'Software Atelier III' the number of ' ' chars should be 2");
equal(a["F"] , 1, "For the String 'Software Atelier III' the number of 'F' chars should be 1");
equal(a["W"] , 1, "For the String 'Software Atelier III' the number of 'W' chars should be 1");
equal(a["T"] , 2, "For the String 'Software Atelier III' the number of 'T' chars should be 2");
equal(a["L"] , 1, "For the String 'Software Atelier III' the number of 'L' chars should be 1");
});
SOLUTION: Thanks to h2ooooooo
So for my code I used
function letter_frequency(s) {
if(s === undefined){
return undefined
} else {
var fr = {};
for (var i = 0; i < s.length; i++) {
var ch = s.charAt(i).toUpperCase();
if (fr[ch]) {
fr[ch]++;
} else {
fr[ch] = 1;
}
}
}
return freq;
}
I linked some code from all the answer I received. The only difference is the control for the undefined question where my exercise asked for a control with undefined words