Write a function that accepts a string argument and removes duplicate characters that are neighbors. If the new string also has duplicate neighbors, those should be removed also.
reduce_dups('abb') => "a"
reduce_dups('abba') => ""
reduce_dups('aba') => "aba"
We can solve this problem by using a loop to find duplicate touching characters. When we find a set of duplicate touching characters, we can concat all the characters before the dups, and all the characters after the dups, creating a new string. Then we reset our variables to run a new loop, on our newly created string, repeating the steps above.
function reduce_dups(str) {
let prev = undefined
for (let i = 0; i < str.length; i++) {
if (!prev) {
prev = str[i]
} else if (str[i] === prev) {
let before_dups = str.slice(0, i - 1)
let after_dups = str.slice(i + 1, str.length)
str = before_dups + after_dups
i = -1
prev = undefined
} else {
prev = str[i]
}
}
return str
}
reduce_dups('abba') // ''
reduce_dups('aab') // 'b'
reduce_dups('aba') // 'aba'