0

So I have the following code, from which I expect the x function to return null after being called 3 times but it keeps returning the the same function:

const repeat = (n, tailFn) => {
  for (let i = 0; i < n; i++) {
    tailFn = () => tailFn;
  }
  return tailFn;
};

const x = repeat(2, x => null);

console.log(x());           // function tailFn() { return _tailFn }
console.log(x()());         // function tailFn() { return _tailFn }
console.log(x()()()()()()); // function tailFn() { return _tailFn }

What am I doing wrong? See it on CodePen.

2 Answers 2

6

Your function just assigns () => tailFn to tailFn three times and then returns it. Instead, you should return a function which returns repeat(n - 1, tailFn) if n is not 0, and tailFn otherwise.

const repeat = (n, tailFn) => {
  return n !== 0 ? () => repeat(n - 1, tailFn) : tailFn;
};

const x = repeat(2, x => null);

console.log(x());           // () => repeat(n - 1, tailFn)
console.log(x()());         // x => null
console.log(x()()());       // null

Sign up to request clarification or add additional context in comments.

Comments

4

You have created a function that ALWAYS returns itself,

tailFn=()=>tailFn;

actually the loop is meaningless.Its behavior is similar to a recursive function without a base case.

2 Comments

Am I not creating a new function tailFn that is returning the old tailFn?
I think I got it. I just need to keep tailFn in another variable and return that from new tailFn;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.