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

328
Vistas
JS Class. Nesting methods work, but chaining doesn't

trying to complete my task - create HTML builder. It works almost fine, but when I try test chaining case - throws Error. I understand that I need to return object to make chaining work, and we can create our custom toString(). But in this case I don't know where to save html strings data.

class Templater {
    transform(tags) {
        return tags.join("");
    }
    //function returns array where [0] = atttibutes, [1] = innerText or innerNodes
    attributesCheck(tags) {
        let attributeObject = {};
        tags.forEach((item) => {
            if(typeof item === 'object' && item !== null && !Array.isArray(item)) {
                attributeObject = item; 
            }
         })
         const content = tags.filter(item => typeof item !== 'object')
        let objectArr = Object.entries(attributeObject);
        let classIndex; 
        let idIndex;
        objectArr.forEach((item, index) => {
            if(item[0] === 'class') {
                classIndex = index; 
            }
            if (item[0] === 'id') {
                idIndex = index; 
            }
        })
        const classItem = objectArr[classIndex]; 
        const idItem = objectArr[idIndex]; 
        objectArr = objectArr.filter(item => item[0] !== 'class' && item[0] !== 'id')
        if (idItem) {
            objectArr.unshift(idItem); 
        }
        if (classItem) {
            objectArr.unshift(classItem); 
        }
       
        let attrString = ''; 
        objectArr.forEach(item => {
            attrString += ` ${item[0]}="${item[1]}"`
        })

        return [attrString, content]; 
    }

    div(...tags) {
        return `<div${this.attributesCheck(tags)[0]}>${this.transform(this.attributesCheck(tags)[1])}</div>`;
    }
    span(...tags) {
        return `<span${this.attributesCheck(tags)[0]}>${this.transform(this.attributesCheck(tags)[1])}</span>`;
    }
    br(argument) {
        if (argument) {
            throw new Error('Nested content is not allowed');
        } else {
            return `<br>`;
        }
    }
    p(...tags) {
        return `<p${this.attributesCheck(tags)[0]}>${this.transform(this.attributesCheck(tags)[1])}</p>`;
    }
}

const template = new Templater(); 
console.log(template.div('1454', {id: 'fixing'}).toString());
console.log(template.div('World of Templates', {id: "card", class: 'first'}).toString());

//nesting works
console.log(template.div(
    template.p('Hello', {id: 'fix', class: "first-p"}),
    template.p('World')
).toString());

//chaining DOESN'T
template.span('Hello').span('World').toString()

about 4 years ago · Juan Pablo Isaza
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