Length

in ita •  21 days ago 

export function encode(text:string) {
let res = "";
let num = 1;
for(let i=0; i<text.length; i++){
if(i<text.length - 1 && text[i] === text[i+1]){
num +=1;
}
else{
if(num === 1){
res += text[i];
}

      else {
      res += (num.toString() + text[i]);
      num = 1;
    }
}

}
return res;
}

export function decode(text:string) {
let res = "";
let tras = "";
let counter = 0;
for(let i=0; i<text.length; i++){
if (/^\d$/.test(text[i])){
tras += text[i];}

else{
    if(tras !== ""){
      counter = parseInt(tras,10);
      for( let j=0; j< counter-1; j++){
        res += text[i];
      } 
    tras = "";
}
res += text[i];
}

}
return res;
}

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!