const availableTags = ['div', 'h1', 'p', 'span'];
function tagsCollector() {
this.tags = [];
this.addTag = function(tag) {
this.tags.push(tag);
}
}
class Format {
constructor() {
this.tags = new tagsCollector();
}
}
availableTags.forEach(tag => {
Object.defineProperty(Format.prototype, tag, {
value: new Proxy(text => {
return `
<${tag}>
<${this.tags.reduceRight((html, curtag) => {
return `<${curtag}>${html}</${curtag}>`;
}, text)}
</${tag}>
`
}, { get: (_, props) => {
this.tags.addTag(tag);
return this;
}})
})
})
The challenge is field related HTML formatting from codewars. We need to implement the fluent interface pattern of the Format.div.p ('text') type. For each tag, I create a getter that takes the tag of the tag into tagCollector and returns the current Format object. Thought to proxy the getter, but then the call is lost and I cannot access this.tags.