truncateArgs.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 {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. } else {
  29. return [args[0].slice(-availableLength)];
  30. }
  31. }
  32. // Check if there is space for at least 4 chars per arg
  33. if (availableLength < arraySum(lengths.map(i => Math.min(i, 6)))) {
  34. // remove args
  35. if (args.length > 1)
  36. return truncateArgs(args.slice(0, args.length - 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. } else {
  72. return "";
  73. }
  74. });
  75. };
  76. module.exports = truncateArgs;