1

I'm very new to js and figuring out how to console.log what i want instead of "null" gave me a small headache.

I have this code (it's from a book called "Eloquent JavaScript")

function findNumber(number) {
function checkingForSolution(current, history) {
    if (current == number) {
        return history;
    } else if (current > number) {
        return null;
    } else {
        return (
            checkingForSolution(current + 5, `(${history} + 5)`) ||
            checkingForSolution(current * 3, `(${history} * 3)`)
        );
    }
}

return checkingForSolution(1, '1');
} 
console.log(findNumber(34));

It finds a number by either multiplying it by 3 or adding 5 to it. I would like to add console.log so it would print something like "sorry could not find algorithm" instead of "null"

The problem i couldnt solve is that if i check for null value in function, it just prints the console.log instead of algorithm when algorithm could be found. When the funcion is searching for the solution it gets multiple "nulls"

I tried something like this

if(findNumber.checkingForSolution == null){
console.log('sorry')
}
else{console.log(findNumber(34));
}

But even tho the algorithm COULD be found it just prints "sorry" Could someone help?

Hapay
  • 15
  • 4

1 Answers1

2

You could add the default value after the first call of the recursive function.

Inside of checkingForSolution, any replacement of null into a truthy value would stop the search for a valid value prematurely.

function findNumber(number) {
    function checkingForSolution(current, history) {
        if (current == number) return history;
        if (current > number) return null;
        return checkingForSolution(current + 5, `(${history} + 5)`)
            || checkingForSolution(current * 3, `(${history} * 3)`);
    }

    return checkingForSolution(1, '1')
        || "sorry could not find algorithm";
}

console.log(findNumber(34));
console.log(findNumber(2));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Wow thank You, I would probably not figure that out. I tried a lot of things but not the OR operator. Thank you so much for your time :) – Hapay Sep 24 '20 at 08:44