truncateArgs.js 2.3 KB

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