-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexgen.js
99 lines (71 loc) · 2.29 KB
/
indexgen.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const data = require('./indexdata.json')
const path = require('path')
const fs = require('fs')
const { prettyCapitalize } = require('./pretty-capitalize')
const URL_PREFIX = 'github.com/ChrisVilches/Algorithms/blob/main/'
const IGNORE_DIR_PATTERNS = [
'.git/',
'.vscode/',
/\.md/
]
function shouldIgnore (path) {
for (let i = 0; i < IGNORE_DIR_PATTERNS.length; i++) {
if (path.search(IGNORE_DIR_PATTERNS[i]) !== -1) return true
}
return false
}
function getAllFiles (directory) {
const files = []
const dfs = (directory) => {
fs.readdirSync(directory).forEach(file => {
const absolute = path.join(directory, file)
if (shouldIgnore(absolute)) return
if (fs.statSync(absolute).isDirectory()) {
dfs(absolute)
} else {
files.push(absolute)
}
})
}
dfs(directory)
return files
}
const normalizeString = x => x.replace(/[^a-zA-Z0-9\s]/g, ' ').replace(/\s+/g, ' ').toLowerCase()
function findUniqueFilePath (simplifiedFilename, allFiles) {
let found = null
simplifiedFilename = normalizeString(simplifiedFilename)
for (let i = 0; i < allFiles.length; i++) {
const file = allFiles[i]
if (normalizeString(file).search(simplifiedFilename) !== -1) {
if (found != null) throw new Error(`Multiple matches for "${simplifiedFilename}": "${found}" and "${file}"`)
found = file
}
}
if (found == null) throw new Error(`Not found: ${simplifiedFilename}`)
return found
}
const toLink = x => 'https://' + path.join(URL_PREFIX, x)
function generateIndex () {
const allFiles = getAllFiles('./')
let printNewLine = false
const lines = []
data.forEach(category => {
if (printNewLine) lines.push('')
printNewLine = true
lines.push(`### ${prettyCapitalize(category.header)}`)
category.items.forEach(item => {
lines.push(`\n${prettyCapitalize(item.title)}\n`)
const files = item.files
.map(f => findUniqueFilePath(f, allFiles))
if (files.length !== (new Set(files).size)) {
throw new Error(`Files in "${category.header}" -> "${item.title}" are not unique`)
}
files.sort((a, b) => a === b ? 0 : (a < b ? -1 : 1))
.forEach(file => lines.push(`* [${file}](${toLink(file)})`))
})
})
return lines.join('\n')
}
module.exports = {
generateIndex
}