-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringify.js
More file actions
50 lines (46 loc) · 1.1 KB
/
stringify.js
File metadata and controls
50 lines (46 loc) · 1.1 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
export const stringify = (val) => {
if (val === null) throw TypeError(`Unexpected null`)
if (typeof val === 'string') return esc(val)
if (Array.isArray(val)) {
let ret = ''
for (const it of val) {
ret += `[${stringify(it)}]`
}
return ret
}
if (typeof val === 'object') {
let ret = ''
for (const [k, v] of Object.entries(val)) {
ret += `${esc(k)}[${stringify(v)}]`
}
return ret
}
throw TypeError(`Unsupported type: ${typeof val}`)
}
const esc = (str) => {
let h = 0
const parts = []
if (str === '\\') return '\\[\\]'
for (let i = 0; i < str.length; ++i) {
const c = str[i]
if (c === '[') {
parts.push(str.slice(h, i), '[{]')
h = i + 1
}
else if (c === ']') {
parts.push(str.slice(h, i), '[}]')
h = i + 1
}
}
const tail = str.slice(h)
if (parts.length > 0) return `\\[${parts.join('')}${tail}]`
return tail
}
export const stringifytree = (tree) => {
let ret = ''
const {subs, text} = tree
for (const {text, tree} of subs) {
ret += text + '[' + stringifytree(tree) + ']'
}
return ret + text
}