You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.4 KiB

4 years ago
  1. 'use strict';
  2. exports.type = 'perItem';
  3. exports.active = true;
  4. exports.description = 'Sorts children of <defs> to improve compression';
  5. /**
  6. * Sorts children of defs in order to improve compression.
  7. * Sorted first by frequency then by element name length then by element name (to ensure grouping).
  8. *
  9. * @param {Object} item current iteration item
  10. * @return {Boolean} if false, item will be filtered out
  11. *
  12. * @author David Leston
  13. */
  14. exports.fn = function(item) {
  15. if (item.isElem('defs')) {
  16. if (item.content) {
  17. var frequency = item.content.reduce(function (frequency, child) {
  18. if (child.elem in frequency) {
  19. frequency[child.elem]++;
  20. } else {
  21. frequency[child.elem] = 1;
  22. }
  23. return frequency;
  24. }, {});
  25. item.content.sort(function (a, b) {
  26. var frequencyComparison = frequency[b.elem] - frequency[a.elem];
  27. if (frequencyComparison !== 0 ) {
  28. return frequencyComparison;
  29. }
  30. var lengthComparison = b.elem.length - a.elem.length;
  31. if (lengthComparison !== 0) {
  32. return lengthComparison;
  33. }
  34. return a.elem != b.elem ? a.elem > b.elem ? -1 : 1 : 0;
  35. });
  36. }
  37. return true;
  38. }
  39. };