I have r = to how many times can letter be repeated in a row and s = to string to check.
For example if s = "aaabbbccc777" and r = 2. result = "aabbcc77".
I need it to be dynamic and as easy and clean as possible.
Thanks for the help in advance.
let s = "bbbaaaccc777cdggg";
let r = 2;
const verification = (s, r) => {
}
verification(s, r);
CodePudding user response:
You can iterate over the string like this:
const verification = (s, r) => {
let res = '', last = null, counter = 0;
s.split('').forEach(char => {
if (char == last)
counter ;
else {
counter = 0;
last = char;
}
if (counter < r)
res = char;
});
return res;
}
CodePudding user response:
I guess this is the cleanest way of doing it. It uses an occ
object to count the occurrences:
const
str = "bbbaaaccc777cdggg",
rows = 2;
const verification = (s, r) => {
const occ = {};
let newStr = "";
for (const char of str) {
if (!occ[char])
occ[char] = 0;
if (occ[char] < r)
newStr = char;
// Count occurrences
occ[char];
}
return newStr;
};
console.log(verification(str, rows));