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');
CodePudding user response:
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'))
CodePudding user response:
function encoded(plainText) {
let charMap = {}
for (let char of plainText) {
char = char.toLowerCase()
if (!charMap[char]) {
charMap[char] = 1
} else {
charMap[char]
}
}
let output = '';
for (const [key, value] of Object.entries(charMap) ) {
output = `${value}${key}`;
}
console.log(output)
}
encoded('aaabbcccc');
CodePudding user response:
Maintain the count in a variable and test if the next letter in the sequence matches the current letter resetting the count if it's not.
function encoded(plainText) {
let out = '';
let count = 0;
const text = plainText.toLowerCase();
for (let i = 0; i < text.length; i ) {
count;
if (text[i 1] !== text[i]) {
out = `${count}${text[i]}`;
count = 0;
continue;
}
}
return out;
}
console.log(encoded('aaabbccccABBCc'));