This code is confused.
First off, while it's called newtonRaphson
, it seems to be only for a very specific case of the Newton-Raphson method, that of finding square roots using the Babylonian Method. So ideally it should have a better name.
It tries to simultaneously solve the problem recursively and with a while
-loop. We need to choose one or the other. Here we choose a recursive version.
Then we note that these lines make no real sense:
var previousValue = 0
if(previousValue === 0){
previousValue = x/2
}
This is a ridiculously round-about way of writing
var previousValue = x/2
You ask about doing this without passing the previous value to the recursive function. You could, just by tracking it at a higher scope. (Please, please, not the global scope!) It might look like this:
const sqrt = (x, count) => {
let prev = x / 2
const _sqrt = (count) => {
if (count <= 0) return prev
prev = (prev + (x / prev)) / 2
return _sqrt (count - 1)
}
return _sqrt (count)
}
console .log (sqrt (25, 1)) //=> 7.25
console .log (sqrt (25, 2)) //=> 5.349137931034482
console .log (sqrt (25, 3)) //=> 5.011394106532552
console .log (sqrt (25, 4)) //=> 5.000012953048684
console .log (sqrt (25, 5)) //=> 5.000000000016778
console .log (sqrt (25, 6)) //=> 5
But I would not recommend this at all. Recursion is simplest when you pass the necessary variables into the function. And this is not hard to do, either with a defaulted parameter, like this:
const sqrt = (x, count, prev = x / 2) =>
count <= 0
? prev
: sqrt (x, count - 1, (prev + (x / prev)) / 2)
or with a public wrapper around an internal recursive helper function, like this:
const _sqrt = (x, count, prev) =>
count <= 0
? prev
: _sqrt (x, count - 1, (prev + (x / prev)) / 2)
const sqrt = (x, count) =>
_sqrt (x, count, x / 2)
Of the two, I usually prefer the defaulted parameter, but there are some potential problems with them, especially if you are not in control of how your function is called. Then the public/internal split makes sense.