I am trying to determine groups in a string.
For example "AAABBCCCCD" should have ["AAA", "BB", "CCCC", "D"] as groups based on the pattern in the string.
Here is my simple function to do that:
const patternGroup = (str) => {
let cursor = str[0]
let groups = []
let currentGroup = ""
for (let i = 0; i < str.length; i++) {
let ch = str[i]
if (ch === cursor) {
currentGroup += ch
}
else {
groups.push(currentGroup)
currentGroup = ch
cursor = ch
}
}
if (currentGroup !== "") {
groups.push(currentGroup)
}
return groups
}
It works as intented but I am looking for a simpler function, maybe using map/reduce or regex. Any ideas?
