I solve problems that are set at the interview.
Required : write a recursive function that flips a string.
I independently decided in two ways that were different from each other, but which one is preferable and why I cannot determine without your help.
And I would be glad to see more optimal options.
I method:
function repl_str(str) { if (typeof str == "string") str = { str: str, index: 0, buff: "" }; else if (str.index >= str.str.length) return str.buff; str.buff += str.str.substring(str.str.length - (str.index + 1), str.str.length - str.index); str.index++; return repl_str(str); } repl_str("test"); //tset
II method:
function repl_str(str, stack) { if (typeof stack == "undefined") { stack = {}; stack.index = 0; stack.buff = ""; } else if (stack.index >= str.length) return stack.buff; stack.buff += str.substring(str.length - (stack.index + 1), str.length - stack.index); stack.index++; return repl_str(str, stack); } repl_str("test"); //tset