Last active
June 2, 2017 15:41
-
-
Save alejandrolechuga/a7ccb7b1f45b1cf79fdc0c4a22db4c60 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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