- Input:
aHtuE
- Expected Output:
A-Hh-Ttt-Uuuu-Eeeee
- Actual Output:
A-HH-Ttt-Uuuu-Eeeee
The function takes a string (in this example "aHtuE") and the output should be "A-Hh-Ttt-Uuuu-Eeeee". However the second "h" in this example appears in upper case instead of lower case. I guess it’s a counting problem or so, but whatever I try, I don’t get it.
function accum(s) {
// Fill char with first character in upper case
let char = (s.substring(0, 1)).toUpperCase();
let result = "";
for (i = 1; i <= s.length; i++) {
// Add '-'
result += char + "-";
// Get next char
char = s.substring(i, i + 1)
// For counting char
for (j = 1; j <= i; j++) {
// For putting each first new char in upper case
if (j === 1) {
char = char.toUpperCase();
result += char;
}
// else lower case
else {
char = char.toLowerCase();
result += char;
}
}
}
// Remove last '-' char and return result
return result.substring(0, result.length - 1);
}
console.log(accum("aHtuE"))
2
Answers
You can do this as:
or
When you enter the next iteration of the loop, you also add the previous
char
to your result. In case of theH
this is still an uppercaseH
because for theH
you never entered the branch where it was converted to lowercase because for theH
the outer loops indexi == 1
and thus, yourj
will not get> 1
…The fix is easy: Add the correct number of the respective character within the same iteration of the outer loop … See the
//********
comments in the code for changes