-
Notifications
You must be signed in to change notification settings - Fork 0
/
count.ts
98 lines (84 loc) · 2.52 KB
/
count.ts
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
import * as fs from 'fs';
/**
* Returns an array of file names in the root directory.
* @param root A path to root directory.
*/
function getFolders(root: string): string[] {
return fs.readdirSync(root);
}
/**
* Returns a filtered array of folders by name.
* @param folders A string of folder names.
* @param name A substring to filter by.
*/
function filterFolders(folders: string[], name: string): string[] {
return folders.filter((item) => item.includes(name));
}
interface FilesObject {
[k: string]: number;
}
/**
* Returns an object, where keys are folder names
* and values are number of subfolders.
* @param folders A string of folder names.
*/
function getFilesObj(folders: string[]): FilesObject {
return folders.reduce((obj, path) => {
const innerFolders = getFolders(path);
// @ts-ignore
obj[path] = innerFolders.filter(folder => !folder.includes('_example')).length;
return obj;
}, {});
}
/**
* Returns a sum of all files in every folder.
* and values are number of subfolders.
* @param filesObj An object, where keys are subfolders
*/
function getTotalFiles(filesObj: FilesObject) {
let total = 0;
for (let key in filesObj) {
total += filesObj[key];
}
return total;
}
/**
* Reads and returns a string from a file.
* @param filePath
*/
function getFileString(filePath: string): string {
return fs.readFileSync(filePath, { encoding: 'utf8' });
}
/**
* Returns a string with new amounts of kata solved
* @param str A string from readme.
* @param filesObj An object, where keys are subfolders
*/
function refreshFilesCount(str: string, filesObj: FilesObject): string {
const re = (value: string) => {
const regex = `(?<=${value}.+: )\\d+`;
return new RegExp(regex, 'g');
};
for (let path in filesObj) {
str = str.replace(re(path), () => filesObj[path].toString());
}
str = str.replace(re('Total'), () => getTotalFiles(filesObj).toString());
return str;
}
/**
* Writes new data to a file
* @param filePath A path to file.
* @param str New string to write.
*/
function writeFileString(filePath: string, str: string): void {
fs.writeFileSync(filePath, str);
}
function main(): void {
const folders = getFolders('./');
const filteredFolders = filterFolders(folders, 'kyu');
const filesObj = getFilesObj(filteredFolders);
const oldReadme = getFileString('./README.md');
const newReadme = refreshFilesCount(oldReadme, filesObj);
writeFileString('./README.md', newReadme);
}
main();