Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
How to nest and chain my class functions with pure JS?

How can I make such code parts work? Trying to complete task with custom HTML builder - it needs to support chaining and nesting. Understand that I need to return this, but how then to output string with HTML?

// nesting
    const template = Templater().div(
     Templater().p('Hello'),
     Templater().p('World')
    )
    console.log(template.toString())
// chaining 
console.log(Templater().br('error').toString())

example of Class that I try to create:

    class Templater {
    constructor() {}
    div(tags) {
        return `<div>${tags}</div>`
    }
    span(tags) {
        return `<span>${tags}</span>`
    } 
    br(argument) {
        if(argument) {
            return new Error('Nested content is not allowed');
        } else {
            return '<br>'
        }
    } 
    p(tags) {
        return `<p>${tags}</p>`
    } 
}

Have no idea what I need to do.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Sounds like you primarily need a custom toString method that returns the state of the tags called so far.

You'll also need to change the class to a function, because classes cannot be used without new.

const templater = () => {
  let markup = '';
  const transform = tags => tags.join('');
  return {
    div(...tags) {
      markup += `<div>${transform(tags)}</div>`
      return this;
    },
    span(...tags) {
      markup += `<span>${transform(tags)}</span>`
      return this;
    },
    br(argument) {
      if (argument) {
        throw new Error('Nested content is not allowed');
      } else {
        markup += '<br>'
        return this;
      }
    },
    p(...tags) {
      markup += `<p>${transform(tags)}</p>`
      return this;
    },
    toString() {
      return markup;
    },
  };
};

// nesting
const template = templater().div(
  templater().p('Hello'),
  templater().p('World')
)
console.log(template.toString())
console.log(templater().br('error').toString())

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda