learningjavascriptks learningjavascriptks - 3 months ago 6
Javascript Question

I cannot return the real variable on processed recursion?

I have been doing this recursion on eloquent javascript, however I cannot return the real value of variable on return, it is returning the processed value. The code is doing it's job but it's returning the processed variable on recursion. I tried to store the variable on x, but I still fail.

I want to return the last call stack to get the real variable.

this code returns '0 is Even' '1 is even', which I want to return the real argument?

function isEven(x) {
debugger;
var y =x;
if (x<0) {
x = x * -1;
}
if(x===0) {
return console.log(y+' is Even');
} else if(x===1) {
return console.log(y+' is Odd');
} else

return isEven(x-2);
}

// →
console.log(isEven(10));
console.log(isEven(-11));

Answer

You cannot access the initial value using your code.

The simplest way to achieve this goal is to add a function parameter, which will store the original value:

function isEven(x, initial) {
 initial = initial || x; // so that isEven(10) => isEven(10, 10)

if (x<0) {
   x = x * -1; 
}
  if(x===0) {
        return initial+' is Even';
    } else if(x===1) {
        return initial+' is Odd';
    } else 

  return isEven(x-2, initial); 
}

// →
console.log(isEven(10));
console.log(isEven(-11));

However, the correct solution is to separate the initial call and recursive calls. For example, it can be achieved using nested functions.
It is also a good idea to abstract logics (boolean) and displayed information (string).

function isEvenString(initial) {
  function isEvenBool(x) {
    if (x < 0) {
      x = x * -1;
    }

    if (x === 0) {
      return true;
    }

    if (x === 1) {
      return false;
    }

    return isEvenBool(x - 2);
  }

  return initial + (isEvenBool(initial) ? " is Even" : " is Odd");
}

// →
console.log(isEvenString(10));
console.log(isEvenString(-11));

P.S. Note that this isEven function is good for education purposes, but absolutely useless in practice. It takes 1 000 000 function calls to determine that 2 000 000 is even whilst it can be done using one line of code in O(1) operations:

function isEvenString(x) { 
  return x % 2 === 0; 
}