-
Notifications
You must be signed in to change notification settings - Fork 3
/
dom-api-question.js
114 lines (97 loc) · 2.65 KB
/
dom-api-question.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* For more programming concepts, questions, tips, and tutorials, visit:
*
* https://bit.ly/devtools-yt
* https://code.devtools.tech
* https://devtools.tech
*
* Author: Yomesh Gupta (https://yomeshgupta.com)
*/
/**
* Question: Implement the following code so that when interviewer calls vDocument.render()
* then following HTML structure should be printed.
*
* const vDocument = new VDocument();
* const body = vDocument.createElement("body");
* const div = vDocument.createElement("div");
*
* div.innerHTML = "Hello, I am a div!";
*
* body.appendChild(div);
* vDocument.appendChild(body);
*
* vDocument.render();
*
* Output:
* <html>
* <body>
* <div>
* Hello, I am a div!
* </div>
* <body>
* </html>
*
* To understand the solution, visit: https://www.youtube.com/watch?v=CAzMsXUe2I0
*/
// Solution
const INDENT_SIZE = 4;
const getSpaces = (length) => {
return new Array(length).fill(" ").join("");
};
class Node {
constructor(name) {
this.name = name;
this.innerHTML = "";
this.children = [];
}
appendChild(node) {
this.children.push(node);
}
}
class VDocument extends Node {
constructor() {
super("html");
}
createElement(nodeName) {
return new Node(nodeName);
}
render() {
function printTree(currentNode, currentLevel) {
// calculating the prefix spaces for current level
const spaces = getSpaces(currentLevel * INDENT_SIZE);
let output = "";
// opening tag
output += `${spaces}<${currentNode.name}>\n`;
// innerHTML handling
if (currentNode.innerHTML) {
output += `${spaces}${getSpaces(INDENT_SIZE)}${
currentNode.innerHTML
}\n`;
}
// loop for children
for (let i = 0; i < currentNode.children.length; i++) {
output += printTree(currentNode.children[i], currentLevel + 1);
}
// closing tag
output += `${spaces}</${currentNode.name}>\n`;
return output;
}
console.log(printTree(this, 0));
}
}
const vDocument = new VDocument();
const body = vDocument.createElement("body");
const div = vDocument.createElement("div");
div.innerHTML = "Hello, I am a div!";
body.appendChild(div);
// Dynamic Insertion by the interviewer
/*
const div1 = vDocument.createElement("div");
const div2 = vDocument.createElement("div");
div1.innerHTML = "Hello, I am a div 1!";
div2.innerHTML = "Hello, I am a div 2!";
div.appendChild(div1);
body.appendChild(div2);
*/
vDocument.appendChild(body);
vDocument.render();