Rurohi53
Rurohi53

Reputation: 122

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.

Upvotes: 0

Views: 275

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371178

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())

Upvotes: 2

Related Questions