-
Notifications
You must be signed in to change notification settings - Fork 2
/
ascii_tree_generator.html
81 lines (71 loc) · 1.88 KB
/
ascii_tree_generator.html
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
---
layout: default
---
<h1 class="font-bold text-2xl mb-4">Ascii Tree Generator</h1>
<div class="flex justify-between" style="min-height: 75vh">
<textarea id="input" class="w-80 border p-4 bg-gray-100"></textarea>
<pre id="output" class="p-4 grow bg-gray-600 text-gray-300"></pre>
</div>
<script>
function normalize(node, idx, nodes) {
const from = idx ? nodes[idx - 1].level : -1;
const to = node.level;
const results = [];
for (let i = from + 1; i < to; i++) {
results.push({ level: i });
}
results.push(node);
return results;
}
function parse(text) {
const nodes = [].concat(
...text
.split(/\r?\n/)
.filter(line => line.startsWith('#'))
.map(line => ({
level: line.replace(/^(#+).*/, '$1').length - 1,
text: line.replace(/^#+/, '').trim(),
}))
.map(normalize)
);
for (let i = 0; i < nodes.length; i++) {
nodes[i].children = nodes[i].children || [];
for (let j = i - 1; j >= 0; j--) {
if (nodes[j].level + 1 === nodes[i].level) {
nodes[j].children.push(nodes[i]);
break;
}
}
}
return nodes.filter(node => !node.level);
}
function gen(nodes = [], level = 0, prefix = '') {
return nodes.map((node, index) => {
const isLast = index === nodes.length - 1;
const line = level ? `${prefix}${isLast ? '└' : '├'}── ` : '';
const nextPrefix = level ? `${prefix}${isLast ? ' ' : '│ '}` : '';
return [
`${line}${node.text || ''}`,
...gen(node.children, level + 1, nextPrefix),
].join('\n');
});
}
function render() {
$output.textContent = gen(parse($input.value)).join('\n');
}
const $input = document.querySelector('#input');
const $output = document.querySelector('#output');
$input.addEventListener('input', render);
$input.value = `
# the
## quick
### brown
## fox
## jumps
### over
#### the
### lazy
## dog
`.trim();
render();
</script>