Recursive string reversal function in javascript?
One line of code using boolean operators.
Explanation: if string exists call the recursion to reduce the string, otherwise fallback to non existing string (last recursive call)
function reverseString(s) {
return s && reverseString(s.slice(1)) + s[0] || s;
}
A tail recursive version, just for kicks (even though JavaScript doesn't perform tail call elimination):
function reverse(str) {
function r(s, acc) {
return (s.length == 0) ? acc : r(s.substr(1), s.charAt(0) + acc);
};
return r(str, '');
};
Something like:
function reverse (str) {
if (str === "") {
return "";
} else {
return reverse(str.substr(1)) + str.charAt(0);
}
}
So the function is recursive as it calls itself to do the work.