-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfinal-bonus.mjs
100 lines (88 loc) · 2.25 KB
/
final-bonus.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
99
100
// 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 filterFiles = ({ extension }) => (list) => (
list.filter(dirent =>
(
!extension &&
dirent.isFile()
) ||
(
dirent.isFile() &&
extension &&
dirent.name.endsWith(extension)
)
)
);
const recurseSubDirectory = (options) => (list) => (
Promise.all(
list.map(async (dirent) => {
if (dirent.isDirectory()) {
list.push(
(await collectFiles({
...options,
directory: resolvePath(options.directory, dirent.name),
}))
);
}
return dirent;
})
)
);
const mapFile = ({ directory }) => list => (
list.map(({ name }) => resolvePath(directory, name))
);
const collectFiles = async (options) => {
const args = {
directory: ".",
collected: [],
extension: false,
...options,
};
const inputDirectory = await fs.readdir(
resolvePath(args.directory),
{
withFileTypes: true
}
);
const actions = [
recurseSubDirectory(args),
filterFiles(args),
mapFile(args),
];
const files = await actions.reduce(
async (list, action) => (
action(await list)
),
inputDirectory
);
args.collected.push(...files);
return args.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,
extension: ".md"
});
log(`Result:`, files);
assert(utilEquals(expected, files));
} catch (err) {
log(err);
}
};
test();