Creé el generador de HTML (¡por fin!)
Solo tiene métodos: crear div, span, p, br.
Como puede ver en console.logs, tiene un comportamiento de anidamiento y encadenamiento.
Y para detectar el anidamiento y el encadenamiento, tengo una instancia de elemento de Clase
Pero no me muestra el retorno correcto cuando tengo la condición de anidamiento.
Necesito ayuda para encontrar el error y obtener resultados en la primera consola.log =
<div><p>Hello</p><p>World</p></div> class Templater { constructor() { this.arr = []; this.nesting = false; } transform(tags) { return tags.join(""); } div(...tags) { tags.forEach(item => { this.nesting = (item instanceof Templater); }); this.arr.push(`<div>${this.transform(tags)}</div>`) return this; } span(...tags) { tags.forEach(item => { this.nesting = (item instanceof Templater); }); this.arr.push(`<span>${this.transform(tags)}</span>`); return this } br(argument) { tags.forEach(item => { this.nesting = (item instanceof Templater); }); if (argument) { throw new Error('Nested content is not allowed'); } else { this.arr.push(`<br>`); return this; } } p(...tags) { tags.forEach(item => { this.nesting = (item instanceof Templater); }); this.arr.push(`<p>${this.transform(tags)}</p>`); return this } toString() { if (this.nesting) { this.nesting = false; let qwe = [...this.arr]; this.arr = []; return qwe[qwe.length-1]; } else { let qwe = [...this.arr]; this.arr = []; return qwe.join(''); } } } const template = new Templater(); console.log(template.div( template.p('Hello'), template.p('World') ).toString()); console.log(template.div().toString()); console.log(template.div('Hello').p('fix').toString());Trabajó para mí con:
console.log(template.div( template.p('Hello').p('World').toString() ).toString());