forked from 17thshard/roshar-map
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse-markdown-sections.js
45 lines (36 loc) · 1.19 KB
/
parse-markdown-sections.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
module.exports = function parseSections (content, ignoreOutsideOfSections) {
let root
const sections = {}
const lines = content.split('\n')
let currentSection
lines.forEach((line) => {
const headerMatch = line.trim().match(/^(#+)\s+(.*?)$/)
if (headerMatch != null) {
const [, hashes, name] = headerMatch
if (hashes.length === 1) {
currentSection = { name: name.trim(), content: '' }
root = currentSection
} else {
currentSection = { content: '' }
sections[name.toLowerCase().trim()] = currentSection
}
return
}
if (currentSection === undefined && ignoreOutsideOfSections === true) {
return
} else if (currentSection === undefined) {
throw new Error('Line found outside of section')
}
currentSection.content += line + '\n'
})
const metadata = {}
if (sections.metadata) {
sections.metadata.content.split('\n').filter(line => line.trim().startsWith('|')).slice(2).forEach((line) => {
const match = line.trim().match(/^\|([^|]+)\|([^|]+)\|$/)
if (match !== null) {
metadata[match[1].trim()] = match[2].trim()
}
})
}
return { root, sections, metadata }
}