Skip to content

Instantly share code, notes, and snippets.

@tavurth
Created June 6, 2019 09:01
Show Gist options
  • Save tavurth/ff3935ee8aec020fd4aef52919edafae to your computer and use it in GitHub Desktop.
Save tavurth/ff3935ee8aec020fd4aef52919edafae to your computer and use it in GitHub Desktop.
Recursive brace reversal
// foo(foo(bar))blim => foobaroofblim
function reverse(string) {
return string
.split('')
.reverse()
.join('');
}
function checkRecursion(input) {
if (input.indexOf('(') > -1) {
return reverseBraces(input, false);
}
if (input.indexOf(')') > -1) {
return reverseBraces(input, false);
}
return input;
}
function reverseBraces(input, isFirstLevel = true) {
// Grab the items outside of the two outer braces
const [first] = input.split('(');
const [last] = input.split(')').slice(-1);
const result = checkRecursion(
// Grab the area between the two outside braces
input.slice(first.length + 1, input.length - last.length - 1),
);
// Entry to recursion we should not reverse the top level
if (isFirstLevel) {
return first + result + last;
}
// We should reverse the internal result and then reverse the whole result
return reverse(first + reverse(result) + last);
}
console.log(reverseBraces('foo(foo(bar))blim'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment