-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphase-three.mjs
98 lines (81 loc) · 2.13 KB
/
phase-three.mjs
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
// Uses Node.js ES Modules see here:
// https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_enabling
import { assert, log } from "console";
import fs from "fs/promises";
import { resolve as resolvePath } from "path";
const utilEquals = (a, b) => (
a.length === b.length &&
a.every((v, i) => v === b[i])
);
const fullFilePath = (dir) => list => (
list.map(filename => resolvePath(dir, filename))
);
const mapFileStats = (list) => (
Promise.all(
list.map(async (file) => {
const stat = await fs.stat(file);
return {
file,
stat,
};
})
)
);
const recurseSubDirectory = (collected) => (list) => (
Promise.all(
list.map(async (item) => {
if (item.stat.isDirectory()) {
list.push(
(await collectFiles(item.file, collected))
);
}
return item;
})
)
);
const onlyFiles = list => (
list.filter(({ stat }) => stat.isFile())
);
const onlyFileType = list => (
list.filter(({ file }) => file.endsWith(".md"))
);
const mapFile = list => list.map(({ file }) => file);
const collectFiles = async (dir, collected = []) => {
const inputDirectory = await fs.readdir(
resolvePath(dir)
);
const actions = [
fullFilePath(dir),
mapFileStats,
recurseSubDirectory(collected),
onlyFiles,
onlyFileType,
mapFile,
];
const files = await actions.reduce(
async (list, action) => (
action(await list)
),
inputDirectory
);
collected.push(...files);
return collected;
}
const test = async () => {
let files = [];
const directory = "./example";
const expected = [
"example/subfolder/super-secret.md",
"example/one.md",
"example/two.md"
].map(file => resolvePath(file));
log(`Collecting files from: ${directory}`);
try {
files = await collectFiles(directory);
log(`Result:`, files);
assert(utilEquals(expected, files));
} catch (err) {
log(err);
}
};
test();