| 1 | class Component { |
| 2 | constructor({ name, props = {}, children = [], textContent }) { |
| 3 | this.name = name; |
| 4 | this.props = props; |
| 5 | this.children = children; |
| 6 | } |
| 7 | |
| 8 | toString(indent = 1, depth = 0) { |
| 9 | const props = Object.entries(this.props).map(([key, value]) => { |
| 10 | if (value === undefined) { |
| 11 | return key; |
| 12 | } |
| 13 | return `${key}="${value}"`; |
| 14 | }); |
| 15 | |
| 16 | const propsString = props.length > 0 ? ` ${props.join(' ')}` : ''; |
| 17 | |
| 18 | const indents = Array(indent * depth) |
| 19 | .fill('\t') |
| 20 | .join(''); |
| 21 | |
| 22 | const childrenString = this.childrenToString(indent, depth); |
| 23 | |
| 24 | return `${indents}<${this.name}${propsString}>\n${childrenString}\n${indents}</${this.name}>`; |
| 25 | } |
| 26 | |
| 27 | childrenToString(indent, depth) { |
| 28 | const childStrings = []; |
| 29 | |
| 30 | const nextDepth = depth + 1; |
| 31 | |
| 32 | const stringChildIndents = Array(indent * nextDepth) |
| 33 | .fill('\t') |
| 34 | .join(''); |
| 35 | |
| 36 | for (const child of this.children) { |
| 37 | if (child.constructor.name === 'String') { |
| 38 | const lines = child.split('\n'); |
| 39 | |
| 40 | const indentedString = lines.map((line) => `${stringChildIndents}${line}`).join('\n'); |
| 41 | |
| 42 | childStrings.push(indentedString); |
| 43 | continue; |
| 44 | } |
| 45 | |
| 46 | const childString = child.toString(indent, nextDepth); |
| 47 | childStrings.push(childString); |
| 48 | } |
| 49 | |
| 50 | const string = childStrings.join('\n'); |
| 51 | |
| 52 | return string; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | module.exports = { Component }; |
nothing calls this directly
no outgoing calls
no test coverage detected