Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
Uexpected Function Behavior. JS Classes

I've created HTML builder (finally!)

It just has methods: create div, span, p, br.

As you can see in console.logs it has nesting and chaining behavior.

And for detecting nesting and chaining I have item instanceof Class
But it doesn't show me correct return when I have nesting condition.

Need help to find the mistake and get output in first console.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());

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Worked for me with :

    console.log(template.div(
        template.p('Hello').p('World').toString()
    ).toString());
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!