-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
66 lines (58 loc) · 1.95 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import fs from 'fs'
import path, { dirname } from 'path'
import _ from 'lodash'
import yaml from 'js-yaml'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const listsPath = path.join(__dirname, 'lists')
const toCamelCase = (str) => {
return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase() })
}
const allLists = fs
.readdirSync(listsPath, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.flatMap(dirent =>
fs.readdirSync(path.join(listsPath, dirent.name))
.filter(file => path.extname(file) === '.yml')
.map(file => {
return {
originalPath: [dirent.name, file.split('.')[0]],
camelCasePath: [toCamelCase(dirent.name), toCamelCase(file.split('.')[0])]
}
})
)
const readListFile = (listPath) => {
const fileContent = fs.readFileSync(`${listsPath}/${listPath.join('/')}.yml`).toString()
const [frontmatter, items] = fileContent.split(/---|\.\.\./).slice(1) // Splits at the YAML frontmatter boundaries
const parsedFrontmatter = yaml.load(frontmatter)
const list = items.split('\n').filter(e => String(e).trim())
return {
title: parsedFrontmatter.title,
category: parsedFrontmatter.category,
list
}
}
const addNestedProperty = (obj, path, getter) => {
const lastKey = path.pop()
path.reduce((nestedObj, key) => {
if (!nestedObj[key]) nestedObj[key] = {}
return nestedObj[key]
}, obj)[lastKey] = getter
}
const listHelpers = {}
// make all lists available as methods
allLists.forEach((listPaths) => {
let cachedList = null
const listGetter = (count) => {
if (!cachedList) {
cachedList = readListFile(listPaths.originalPath)
}
if (typeof count === 'number' && count > 0) {
return _.sampleSize(cachedList.list, count)
}
return cachedList
}
addNestedProperty(listHelpers, [...listPaths.camelCasePath], listGetter)
})
export default listHelpers