-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDocToScript.js
61 lines (47 loc) · 1.22 KB
/
DocToScript.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
60
61
const fs = require('fs')
const { exit, argv } = require('process')
const readFile = () => {
const inputFile = argv[3] || "input.txt"
const buffer = fs.readFileSync(inputFile, 'utf8', (err, data) => {
if (err) {
console.log(err)
exit(1)
}
})
return buffer
}
const parseContent = (content) => {
const lines = content.split('\n')
let pageIdx = 0
let parsed = []
lines.map(tmp => {
const line = tmp.trim()
if (line === '') return
if ((/^page\s+[0-9]+/gi).test(line)) {
const splitted = line.split(' ')
pageIdx = Number(splitted[splitted.length - 1])
}
let page = parsed.find(e => e.page === pageIdx)
if (!page) {
parsed = [...parsed, {page: pageIdx, lines: []}]
page = parsed.find(e => e.page === pageIdx)
}
page.lines.push(line)
})
return parsed
}
(() => {
const fileContent = readFile()
let output = ''
const parsed = parseContent(fileContent)
const formatted = parsed.map(page => {
return page.lines.map((line, idx) => {
if (idx === 0) return ''
return `${page.page}.${line}`
})
})
formatted.forEach(page => {
output += page.join('\n')
})
fs.writeFileSync(`output-${+ new Date()}.txt`, output)
})()