简体   繁体   中英

How to encode string in javaScript

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');

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'))

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'));

 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM