0

I am trying to write a function in JavaScript where there will be an infinite call to greet(). The expected outcome is to have the greetings concatenated with each call.

console.log(greet('hello').greet('world').greet()) 

the output of the above should give Hello world and there might be infinite greet('string')

My initial implementation looked like this:


let greet = function (a) {
  return  function (a) {
        return function (c){
          return c ? (b + " " + c ) : (a + " " + b);
        }
  }
};

However, the output is not as expected. I am facing some issues in the implementation and would like some help in resolving them. Can someone help me fix this issue? Thank you in advance."

Praveen Vishnu
  • 443
  • 1
  • 6
  • 20

4 Answers4

6

Basically, have a function that returns an object with a function inside which in turn invokes the global function that returns an object... etc

let greet = a => ({
    greet: b => b ? greet(a + ' ' + b) : a
})

console.log(greet('hello').greet('world').greet())
gog
  • 10,367
  • 2
  • 24
  • 38
2

The issue in your code is that you are using the variable b inside the innermost function, but it's not defined in the scope of that function. Also, you are declaring a function with the same name a in the inner function, which shadows the outer a parameter.

Here's a corrected version of the code:

let greet = function (a) {
  let b = a;
  return function (c) {
    if (c) {
      b = b + " " + c;
    }
    return {
      greet: function (d) {
        return greet(b + (d ? " " + d : ""));
      }
    };
  };
};

With this code, you can call greet multiple times and concatenate the greetings with each call. For example:

console.log(greet('hello').greet('world').greet());
// Output: "Hello world"
1

You are probably looking for fluent chaining in JavaScript. You can achieve this approach by creating your own custom class and keep returning this:

class Greeter {
  content = '';
  greet(string) {
    this.content += (this.content.length ? ' ' : '') + string;
    return this;
  }
  toString() {
    return this.content;
  }
}

const greeter = new Greeter();
const output = greeter
  .greet('I')
  .greet('can')
  .greet('do')
  .greet('this')
  .greet('forever')
  .toString();
  
console.log(output);

You can check other possibilities by searching it. For example on Stackoverflow are similliar questions.

Jax-p
  • 7,225
  • 4
  • 28
  • 58
0

Thank you all for responding to my issue. i also came up through some implementation with traditional function expressions

here is my solution

 let greet = function (a) {
  return {
    greet: function (b) {
      return b ? greet(a + " " + b) : a;
    }
  }
};
Praveen Vishnu
  • 443
  • 1
  • 6
  • 20