I want to find character sequence count in a given string.
Sample Input: aaaabbbbaaacccbbb
Output: a4b4a3c3b3
My below function is working great and giving me the same result. but can this be optimized?
function getCharCount(str) {
var result = str.charAt(0);
var count = 1;
if (str.length == 1) {
result += count;
return result;
} else {
for(var i=1;i<str.length;i++) {
if(str.charAt(i) != str.charAt(i-1)) {
result += count + str.charAt(i);
count = 1;
} else {
count++;
}
if (i == str.length - 1) {
result += count;
}
}
return result;
}
}