-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathastToHtmlTable.js
More file actions
52 lines (47 loc) · 1.36 KB
/
astToHtmlTable.js
File metadata and controls
52 lines (47 loc) · 1.36 KB
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
export const astToHtmlTable = (ast) => {
return `<table>${rows(ast)}</table>`
}
const rows = (ast) => {
const {subvalues, suffix} = ast
let ret = ''
for (const {prefix, value} of subvalues) {
const [pre, tag, post] = trim(prefix)
if (tag === '') ret += `${pre}<tr>${cells(value, 'td')}</tr>`
else if (tag === '#') ret += `${pre}<tr>${cells(value, 'th')}</tr>`
else throw Error('oops')
}
return ret + suffix
}
const cells = (ast, tag) => {
const {subvalues, suffix} = ast
let ret = ''
for (const {prefix, value} of subvalues) {
const [pre, mid, post] = trim(prefix)
if (mid === '') ret += `${pre}<${tag}>${astToHtml(value)}</${tag}>`
else throw Error('oops')
}
return ret + suffix
}
export const astToHtml = (ast) => {
const {subvalues, suffix} = ast
let ret = ''
for (const {prefix, value} of subvalues) {
const [pre, tag, post] = trim(prefix)
if (tag === '') ret += astToHtml(value)
else ret += `${pre}<${tag}>${astToHtml(value)}</${tag}>`
}
return ret + suffix
}
const trim = (prefix) => {
let i = 0, j = 0
for (; i < prefix.length; ++i) {
if (isWhitespace(prefix[i]) === false) break
}
for (j = i; j < prefix.length; ++j) {
if (isWhitespace(prefix[j])) break
}
return [prefix.slice(0, i), prefix.slice(i, j), prefix.slice(j)]
}
const isWhitespace = (c) => {
return ' \n\r\t'.includes(c)
}