tratando de completar mi tarea: crear un generador de HTML. Funciona casi bien, pero cuando intento probar el caso de encadenamiento, arroja un error. Entiendo que necesito devolver el objeto para que el encadenamiento funcione, y podemos crear nuestro toString() personalizado. Pero en este caso no sé dónde guardar los datos de las cadenas html.
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()