source: trip-planner-front/node_modules/svgo/plugins/sortDefsChildren.js@ 6a80231

Last change on this file since 6a80231 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.8 KB
Line 
1'use strict';
2
3exports.type = 'visitor';
4exports.name = 'sortDefsChildren';
5exports.active = true;
6exports.description = 'Sorts children of <defs> to improve compression';
7
8/**
9 * Sorts children of defs in order to improve compression.
10 * Sorted first by frequency then by element name length then by element name (to ensure grouping).
11 *
12 * @author David Leston
13 *
14 * @type {import('../lib/types').Plugin<void>}
15 */
16exports.fn = () => {
17 return {
18 element: {
19 enter: (node) => {
20 if (node.name === 'defs') {
21 /**
22 * @type {Map<string, number>}
23 */
24 const frequencies = new Map();
25 for (const child of node.children) {
26 if (child.type === 'element') {
27 const frequency = frequencies.get(child.name);
28 if (frequency == null) {
29 frequencies.set(child.name, 1);
30 } else {
31 frequencies.set(child.name, frequency + 1);
32 }
33 }
34 }
35 node.children.sort((a, b) => {
36 if (a.type !== 'element' || b.type !== 'element') {
37 return 0;
38 }
39 const aFrequency = frequencies.get(a.name);
40 const bFrequency = frequencies.get(b.name);
41 if (aFrequency != null && bFrequency != null) {
42 const frequencyComparison = bFrequency - aFrequency;
43 if (frequencyComparison !== 0) {
44 return frequencyComparison;
45 }
46 }
47 const lengthComparison = b.name.length - a.name.length;
48 if (lengthComparison !== 0) {
49 return lengthComparison;
50 }
51 if (a.name !== b.name) {
52 return a.name > b.name ? -1 : 1;
53 }
54 return 0;
55 });
56 }
57 },
58 },
59 };
60};
Note: See TracBrowser for help on using the repository browser.