Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Need help solving this method chaining question?

I got asked this in an Interview and I couldn't solve it. Was wondering if any of you guys can help me.

fn("hello").fn("world").fn("!!!").fn();

function fn (str){
  // Enter Solution Here
}

The solution should return 'hello world !!!'.

I tried method chaining and was able to get a partially right answer which is as follows:

function fn(str) {
    var string = str;
    this.fn1 = function(str1) {
        string += " "+str1;
        return this;
    }
    this.fn = function() {
        console.log(string)
    }
}

new fn("hello").fn1("world").fn1("!!!").fn();

but as you can see I cant get it to work unless I use fn1 as the function to concat the string. Any help will be appreciated, thanks.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Have the function return an object with one fn method. If, when you call it, it has an argument, update the string, otherwise return the string so you can log it.

function fn(str = '') {
  return {
    fn: function (s) {
      if (s) {
        str += ` ${s}`;
        return this;
      }
      return str;
    }
  };
}

const output = fn('hello').fn('world').fn('!!!').fn();
console.log(output);

Additional documentation

  • Template/string literals
about 4 years ago · Juan Pablo Isaza Report

0

You could return an object with two properties, one for returning the complete string and another for collecting parts and retuning the object.

function fn(str) {
    const
        fns = {
            fn: function () {
                return str;
            },
            fn1: function (s) {
                str += ' ' + s;
                return fns;
            }
        };
    return fns;
}

console.log(fn("hello").fn1("world").fn1("!!!").fn());

about 4 years ago · Juan Pablo Isaza Report

0

I think this should do the trick:

function fn(s){
  return new function(){
     this.str = s;
     this.fn = (ns) => {if(ns){this.str += " "+ns; return this;} else return this.str;};
  }
}


let a = fn("hello").fn("world").fn("!!!").fn(); 
console.log(a);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!