-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrontmatter_parser.js
59 lines (50 loc) · 1.46 KB
/
frontmatter_parser.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
import validateFrontmatterLine, { BEGINNING_OF_LIST, KEY_VALUE_PAIR, LIST_ITEM } from './validation'
/**
*
* @param {string} frontmatterString
* @returns {{}}
*/
export default function parseFrontmatter ({ frontmatter: frontmatterString }) {
const parsedFrontmatter = {}
const frontMatterBlankLinesRemoved = frontmatterString
.split(/\n/g)
.map(line => line.trim())
.filter(line => line.length > 0)
const parsedFrontmatterList = frontMatterBlankLinesRemoved.map((line, index, array) => {
const type = validateFrontmatterLine({
line,
index,
array,
nextLine: array[index + 1],
})
return {
type,
line,
}
})
let currentList = ''
parsedFrontmatterList.forEach(parsedFrontmatterLine => {
if (parsedFrontmatterLine.type === KEY_VALUE_PAIR) {
const key = parsedFrontmatterLine.line.split(':', 2)[0].trim()
const value = parsedFrontmatterLine.line
.split(':')
.slice(1)
.join(':')
.trim()
parsedFrontmatter[key] = value
}
if (parsedFrontmatterLine.type === BEGINNING_OF_LIST) {
currentList = parsedFrontmatterLine.line.split(':', 2)[0].trim()
parsedFrontmatter[currentList] = []
}
if (parsedFrontmatterLine.type === LIST_ITEM) {
const value = parsedFrontmatterLine.line
.split('-')
.slice(1)
.join('-')
.trim()
parsedFrontmatter[currentList].push(value)
}
})
return parsedFrontmatter
}