Riadiani Riadiani - 1 month ago 7
Javascript Question

Getting Value from Function in Javascript

I am a beginner at Javascript and am running into a little problem. It is a homework problem, but it is graded based on completion only, so I am only trying to figure out the right answer for myself.

I am supposed to define a function, repeatUntil, that takes in two other functions, say f(returns a number) and g (returns a boolean value). The functionality of repeatUntil is to repeat function f at least once until g returns true.

Here is what I have so far:

function repeatUntil(f, cond) {
var f1;

do{
f1 = f;
return f1;
}
while(cond(f1()));
}


And here is the tester/how we call it:

var print = console.log;
var r = repeatUntil(function(x) { return x + x }, function(x) { return x >= 20 })
print(r(2))
print("Expected: 32")


The function runs, but my problem right now is storing the updated value of x from the repeatUntil function. Right now the function only runs once, and the condition is not updated because I cannot pass in the updated value of x into the function g. I tried putting the result of f() into a variable, but it will only return a function and not a number.

Any help/advice would be greatly appreciated. Thank you!

Answer

Combining the existing comments into an answer.

  • Since you need to call r(), your function needs to return another function.
  • The do loop will run exactly once because you return in the body of the loop

Code

function repeatUntil(f, cond) {
   return function() {
       while(cond(f()));
   }
}
Comments