-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnatural-order.ts
More file actions
84 lines (76 loc) · 1.8 KB
/
natural-order.ts
File metadata and controls
84 lines (76 loc) · 1.8 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { PackageScripts } from "../types";
import { objectFromEntries } from "../utils";
type EntryInfo = {
order: number;
namespace: string;
entry: [string, string];
};
const prepareEntryInfo = (entry: [string, string]) => {
const name = entry[0];
const namespace = name.split(":")[0];
if (name.startsWith("pre")) {
return {
order: 0,
namespace: namespace.substr(3),
entry,
};
}
if (name.startsWith("post")) {
return {
order: 2,
namespace: namespace.substr(4),
entry,
};
}
return {
order: 1,
namespace,
entry,
};
};
export const sortScripts = (scripts: PackageScripts): PackageScripts => {
// prepare namespace and order info
const entries = Object.entries(scripts).map(prepareEntryInfo);
return objectFromEntries(
entries
// make unique namespace groups
.map((e: EntryInfo) => e.namespace)
.filter(
(name: string, i: number, a: Array<string>) =>
a.indexOf(name) === i
)
.sort()
.map((name: string) =>
entries.filter((e: EntryInfo) => e.namespace === name)
)
// sort inside the group
.map((group: Array<EntryInfo>) =>
// sort `1-title` vs `2-title` etc.
group.sort((a: EntryInfo, b: EntryInfo) =>
`${a.order}-${a.entry[0]}`.localeCompare(
`${b.order}-${b.entry[0]}`
)
)
)
// flatten array
.reduce(
(flatted: Array<EntryInfo>, group: Array<EntryInfo>) => [
...flatted,
...group,
],
[]
)
// reduce to entries again
.map((f: EntryInfo) => f.entry)
);
};
export default {
name: "natural-order",
isObjectRule: true,
message: "scripts must be in 'natural' order",
validate: (scripts: PackageScripts) => {
const sorted = sortScripts(scripts);
return Object.keys(sorted).join("|") === Object.keys(scripts).join("|");
},
fix: (scripts: PackageScripts) => sortScripts(scripts),
};