JSFiddle - React, Tailwind, and code Playground
by krustnic
JavaScript
// ('AAABbbbBcCCC') => 'A3Bb3BcC3'
function f(s) {
let ns = ''
let lastChar = s[0]
let count = 1
for(let i=1; i<=s.length; i++) {
const char = s[i]
if (lastChar === char) {
count += 1
} else {
ns += lastChar + (count !== 1 ? count : '')
lastChar = char
count = 1
}
}
return ns
}
const sample = 'AAABbbbBcCCC'
const r = f(sample)
console.log(r)