Currying in javascript multiple calls

Viewed 36

I'm quite clear with the concept of closure in JavaScript but at some point i got confused when i need to solve the questions.

clos() => print("AB")
clos()() => print("ABC")
clos()()() => print("ABCC")
clos()()()() => print("ABCCC")
clos()()()()('xyz') => print("ABCCCxyz")

I have to implement above method in javascript Can someone help me in implementing the above use case.

Solution Tried

 function clos(...n){
   let counter = 0; 
   const initial  = "AB"

   return function(param) {
      counter = counter + 1;

      return initial + "C".repeat(counter)

   };
}
1 Answers

What you are trying to implement is not possible. However, there's one alternative that you can try, which will work.
Here's the code:

function c() {
  this.counter = 0;
  const initial = 'AB';

  this.recursive = function(param) {
    this.counter += 1;

    return typeof param === 'undefined' ? initial + 'C'.repeat(counter - 1) + param : this.recursive;
  }

  return this.recursive
}

As you can see, instead of declaring a temporary variable, we are binding to the function via the this keyword the counter variable.
The question would be, how can the this keyword be used inside the recursive function, since it is not defined anywhere? Well, the reason is because the recursive function it is an anonymous function. From the mdn docs, regarding the name of a function:

The function name. Can be omitted, in which case the function becomes known as an anonymous function.

Anonymous functions do not have a "self", therefore the this keyword does not work in them, it is not defined. What they use instead, it is they closure's self, in this case the c function, which does have a self as it is not an anonymous function, and it has the counter prop defined.

Finally, explaining the code a bit, JS must return a value. In this case, you want to keep returning functions and in the last call return a string. It is not possible to know if which is the last call of the returning function. What we do instead is to pass an argument to the last call, which is what is checked in the ternary operator:

  • If param is not undefined, meaning that a string has been passed, we will keep returning a function.
  • Otherwise, we return the resulting value.

See that we increment the counter value on every call.

Related