Repository navigation
Expand file tree
/
Copy pathFileSort.ts
More file actions
64 lines (50 loc) · 1.74 KB
/
Copy pathFileSort.ts
File metadata and controls
64 lines (50 loc) · 1.74 KB
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
import { Merge } from '@nnode/common'
import { all, Task } from 'promise-parallel-throttle'
import { FileSorter } from './FileSorter'
import { SortOptions } from './SortOptions'
import { SortResults } from './SortResults'
const SORTERS = new Set<FileSorter>()
const DefaultSortOptions: Partial<SortOptions> = {}
interface FileNameSorter {
filename: string
sorters: FileSorter[]
}
export namespace Sorters {
export function register(sorter: FileSorter) {
SORTERS.add(sorter)
}
export function unregister(sorter: FileSorter) {
SORTERS.delete(sorter)
}
export function sorter(filename: string): FileNameSorter {
return {
filename,
sorters: Array.from(SORTERS.values()).filter((sorter) => sorter.sortable(filename)),
}
}
export function sorters(filenames: string[], options: SortOptions): FileNameSorter[] {
return filenames.reduce<FileNameSorter[]>((results, filename) => {
const ignored = options.ignored
.map((expression) => new RegExp(expression, 'i'))
.some((regex) => regex.test(filename))
if (ignored) {
return results
}
return [...results, sorter(filename)]
}, [])
}
export async function sort(filenames: string[], options: Partial<SortOptions> = {}) {
const opts = Merge<SortOptions>(DefaultSortOptions, options)
const sortables = sorters(filenames, opts)
const tasks = sortables.reduce<Task<SortResults>[]>((results, sortable) => {
return [...results, ...sortable.sorters.map((x) => () => x.sort(sortable.filename, opts))]
}, [])
const results = await all(tasks)
return results.reduce<SortResults[]>((errors, current) => {
if (current) {
return [...errors, current]
}
return errors
}, [])
}
}