Skip to content

Instantly share code, notes, and snippets.

@alejandrolechuga
Last active June 2, 2017 15:41
Show Gist options
  • Save alejandrolechuga/a7ccb7b1f45b1cf79fdc0c4a22db4c60 to your computer and use it in GitHub Desktop.
Save alejandrolechuga/a7ccb7b1f45b1cf79fdc0c4a22db4c60 to your computer and use it in GitHub Desktop.
/**
console.log(deepReverse('a1(b2(c1))a1')); // => a1(2b(1c))a1
**/
var string = '1a(2b(c1))a1';
function deepReverse(string, deep){
var length = string.length;
var i = 0;
var collect = [];
var deep = deep || false;
while(i < length) {
if (string[i] === '(') {
var returned = deepReverse(string.substr(i+1), true);
collect.push([].concat('(',returned).join(''));
// skip the returned length
i += returned.length ;
} else if (string[i] === ')' && deep) {
return collect.join('');
} else {
if (deep) {
collect.unshift(string[i]);
} else {
collect.push(string[i]);
}
}
i++;
}
return collect.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment