-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
51 lines (41 loc) · 1023 Bytes
/
index.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
const html = require('mdast-html')
const assert = require('assert')
const mdast = require('mdast')
module.exports = mdjson
// map a markdown string to an object
// with `html` and `raw` fields
// str -> obj
function mdjson (txt) {
assert.equal(typeof txt, 'string', 'input should be a markdown string')
const toHtml = mdast().use(html)
const lexer = mdast()
const tokens = lexer.parse(txt).children
const res = {}
var key = ''
tokens.forEach(function (token, i) {
if (token.type === 'heading') {
key = token.children[0].value
res[key] = []
return
}
if (!key) return
res[key].push(token)
})
Object.keys(res).forEach(function (key) {
const tree = {
type: 'root',
children: res[key]
}
res[key] = {
raw: trimRight(lexer.stringify(tree)),
html: trimRight(toHtml.stringify(tree))
}
})
return res
}
// trim whitespace at the
// end of a string
// str -> str
function trimRight (value) {
return value.replace(/\n+$/, '')
}