javascript - Differentiate between an initial and successive call to a recursive function -
my broad question what's simplest way differentiate between initial , successive call recursive function in javascript.
lemme give example...
let's want following function return false if string passed function in initial call empty. there way without adding in parameter function?
function ispalindrome(str) { if (str.length <= 1) { return true; } if (str.charat(0) !== str.charat(str.length -1)) { return false; } return ispalindrome(str.substr(1, str.length - 2)); } ispalindrome('') // returns true, want return false btw, know above function written more as:
function ispalindrome(str) { return str == str.split('').reverse().join(''); } but i'm reframing recursive function @ broader question here...
don't try distinguish different calls - result of function should not depend on side effects , not on call stack.
instead, use second function little different thing:
function ispalindrome(str) { return str.length <= 1 || str.charat(0) == str.charat(str.length-1) && ispalindrome(str.slice(1, -1)); } function isnonemptypalindrome(str) { return str.length > 0 && ispalindrome(str); }
Comments
Post a Comment