Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda