truncateArgs.js 2.3 KB

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