-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
sortDefsChildren.js
56 lines (55 loc) · 1.76 KB
/
sortDefsChildren.js
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
export const name = 'sortDefsChildren';
export const description = 'Sorts children of <defs> to improve compression';
/**
* Sorts children of defs in order to improve compression.
* Sorted first by frequency then by element name length then by element name (to ensure grouping).
*
* @author David Leston
*
* @type {import('./plugins-types.js').Plugin<'sortDefsChildren'>}
*/
export const fn = () => {
return {
element: {
enter: (node) => {
if (node.name === 'defs') {
/**
* @type {Map<string, number>}
*/
const frequencies = new Map();
for (const child of node.children) {
if (child.type === 'element') {
const frequency = frequencies.get(child.name);
if (frequency == null) {
frequencies.set(child.name, 1);
} else {
frequencies.set(child.name, frequency + 1);
}
}
}
node.children.sort((a, b) => {
if (a.type !== 'element' || b.type !== 'element') {
return 0;
}
const aFrequency = frequencies.get(a.name);
const bFrequency = frequencies.get(b.name);
if (aFrequency != null && bFrequency != null) {
const frequencyComparison = bFrequency - aFrequency;
if (frequencyComparison !== 0) {
return frequencyComparison;
}
}
const lengthComparison = b.name.length - a.name.length;
if (lengthComparison !== 0) {
return lengthComparison;
}
if (a.name !== b.name) {
return a.name > b.name ? -1 : 1;
}
return 0;
});
}
},
},
};
};