This is what I want to do
HTMLConstruct.span('foo'); // -> <span>foo</span>
HTMLConstruct.div.span('bar'); // -> <div><span>bar</span></div>
HTMLConstruct.div.p(
HTMLConstruct.span('bar'),
HTMLConstruct.div.span('baz')
); // -> <div><p><span>bar</span><span>baz</span></p></div>
I made this but it`s not work as it should. I have no idea how to implement it
class TestClass {
private str: string
constructor(str?: string) {
this.str = str || ''
}
div(str: string): TestClass {
str = `<div>${str}</div>`
return new TestClass(str)
}
}
CodePudding user response:
Here's one way you could implement the HTMLConstruct class to make it work as described in your example:
class HTMLConstruct {
elementStack: string[] = []
str: string = ''
constructor(str: string = '') {
this.str = str
}
div(...strs: HTMLConstruct[]): HTMLConstruct {
this.elementStack.unshift('div')
return this.addStrings(strs)
}
span(...strs: HTMLConstruct[]): HTMLConstruct {
this.elementStack.unshift('span')
return this.addStrings(strs)
}
p(...strs: HTMLConstruct[]): HTMLConstruct {
this.elementStack.unshift('p')
return this.addStrings(strs)
}
private addString(str: string): HTMLConstruct {
this.str = `<${this.elementStack.join('><')}>${str}</${this.elementStack.join('></')}>`
return this
}
private addStrings(strs: HTMLConstruct[]): HTMLConstruct {
const str = strs.map(s => s.toString()).join('')
return this.addString(str)
}
toString(): string {
return this.str
}
}
You can then use the HTMLConstruct class like this:
const html = new HTMLConstruct()
console.log(html.span('foo').toString()) // -> '<span>foo</span>'
console.log(html.div().span('bar').toString()) // -> '<div><span>bar</span></div>'
console.log(html.div().p(
html.span('bar'),
html.div().span('baz')
).toString()) // -> '<div><p><span>bar</span><span>baz</span></p></div>'
- The
HTMLConstructclass has astrproperty that holds the current string being constructed. - It also has an
elementStackproperty that holds the elements currently being added to the string. - The
div(),span(), andp()methods all add the corresponding HTML element to theelementStackand return a newHTMLConstructobject with the current string andelementStack. - The
addString()method adds the given string to the current string, using the elements in theelementStackto construct the appropriate HTML tags. It then clears theelementStackand returns the newHTMLConstructobject. - The
addStrings()method is similar toaddString(), but it takes an array ofHTMLConstructobjects and concatenates their strings together before adding them to the current string. - The
toString()method simply returns the current string.
