truncateArgs.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const arraySum = array => {
  7. let sum = 0;
  8. for (const item of array) sum += item;
  9. return sum;
  10. };
  11. /**
  12. * @param {any[]} args items to be truncated
  13. * @param {number} maxLength maximum length of args including spaces between
  14. * @returns {string[]} truncated args
  15. */
  16. const truncateArgs = (args, maxLength) => {
  17. const lengths = args.map(a => `${a}`.length);
  18. const availableLength = maxLength - lengths.length + 1;
  19. if (availableLength > 0 && args.length === 1) {
  20. if (availableLength >= args[0].length) {
  21. return args;
  22. } else if (availableLength > 3) {
  23. return ["..." + args[0].slice(-availableLength + 3)];
  24. } else {
  25. return [args[0].slice(-availableLength)];
  26. }
  27. }
  28. // Check if there is space for at least 4 chars per arg
  29. if (availableLength < arraySum(lengths.map(i => Math.min(i, 6)))) {
  30. // remove args
  31. if (args.length > 1)
  32. return truncateArgs(args.slice(0, args.length - 1), maxLength);
  33. return [];
  34. }
  35. let currentLength = arraySum(lengths);
  36. // Check if all fits into maxLength
  37. if (currentLength <= availableLength) return args;
  38. // Try to remove chars from the longest items until it fits
  39. while (currentLength > availableLength) {
  40. const maxLength = Math.max(...lengths);
  41. const shorterItems = lengths.filter(l => l !== maxLength);
  42. const nextToMaxLength =
  43. shorterItems.length > 0 ? Math.max(...shorterItems) : 0;
  44. const maxReduce = maxLength - nextToMaxLength;
  45. let maxItems = lengths.length - shorterItems.length;
  46. let overrun = currentLength - availableLength;
  47. for (let i = 0; i < lengths.length; i++) {
  48. if (lengths[i] === maxLength) {
  49. const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce);
  50. lengths[i] -= reduce;
  51. currentLength -= reduce;
  52. overrun -= reduce;
  53. maxItems--;
  54. }
  55. }
  56. }
  57. // Return args reduced to length in lengths
  58. return args.map((a, i) => {
  59. const str = `${a}`;
  60. const length = lengths[i];
  61. if (str.length === length) {
  62. return str;
  63. } else if (length > 5) {
  64. return "..." + str.slice(-length + 3);
  65. } else if (length > 0) {
  66. return str.slice(-length);
  67. } else {
  68. return "";
  69. }
  70. });
  71. };
  72. module.exports = truncateArgs;