I am doing an exercise, the task is: I need to write a function which takes an argument a string and returns encoded string, for example: aaabbcccc -> should return 3a2b4c. I wrote the function, I created an object where I have all characters counted but I don’t know how to return value and key converted into the string. Here is my code
function encoded(plainText) { let charMap = {} for (let char of plainText) { char = char.toLowerCase() if (!charMap[char]) { charMap[char] = 1 } else { charMap[char]++ } } console.log(charMap) } encoded('aaabbcccc');
Advertisement
Answer
If your input string could contain duplicate chars, for example aabbbbaaa
, you’d need to use an array of stats for each occurrence of the symbol
Also, object properties do not have order and might be “reorganized” by the runtime for performance reasons. For example, if your input string could contain numbers itself aaa111bbb
function encoded(plainText) { const freq = []; // 1. collect char frequency for each occurrence for (const char of plainText) { const last = freq[freq.length - 1]; if (!last || last.char !== char) { freq.push({ char, count: 1}) } else { last.count++; } } // 2. stringify return freq.reduce((result, { char, count }) => `${result}${count}${char}`, '') } console.log(encoded('aabbbbccccddaa'))