Created
September 30, 2018 08:46
-
-
Save huytd/338b816bba008864086f404f719c5747 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fs from 'fs'; | |
const data = fs.readFileSync('./research.org', 'utf-8'); | |
enum NodeType { HeaderType, TextType }; | |
type NodeLevel = number | null; | |
type NodeValue = string | null; | |
interface Node { | |
nodeType: NodeType; | |
level: NodeLevel; | |
value: NodeValue; | |
childs: Node[]; | |
} | |
let root: Node = { | |
nodeType: NodeType.TextType, | |
level: null, | |
value: null, | |
childs: [] | |
}; | |
const parseHeader = (line: string): Node | null => { | |
let starCount = line.split('').reduce((count: number, char: string) => count + (char === '*' ? 1 : 0), 0); | |
let headerValue = line.split('').reduce((value: string, char: string) => (char !== '*' ? value + char : value), ''); | |
if (!starCount) return null; | |
return { | |
nodeType: NodeType.HeaderType, | |
level: starCount, | |
value: headerValue.trim(), | |
childs: [] | |
}; | |
}; | |
const parseText = (line: string): Node | null => { | |
if (line[0] === '*') return null; | |
let value = line.trim(); | |
if (!value.length) return null; | |
return { | |
nodeType: NodeType.TextType, | |
level: -1, | |
value: value, | |
childs: [] | |
}; | |
}; | |
let parent: Node = root; | |
let current: Node = root; | |
const lines: string[] = data.split('\n'); | |
lines.forEach((line: string) => { | |
let header = parseHeader(line); | |
if (header) { | |
if (current.level < header.level) { | |
current.childs.push(header); | |
parent = current; | |
current = header; | |
} else if (current.level === header.level) { | |
parent.childs.push(header); | |
current = header; | |
} else if (current.level > header.level) { | |
current = parent; | |
current.childs.push(header); | |
current = header; | |
} | |
} else { | |
let text = parseText(line); | |
if (text) { | |
current.childs.push(text); | |
} | |
} | |
}); | |
console.log(JSON.stringify(root)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment