1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- "use strict";
- const arraySum = array => {
- let sum = 0;
- for (const item of array) sum += item;
- return sum;
- };
- const truncateArgs = (args, maxLength) => {
- const lengths = args.map(a => `${a}`.length);
- const availableLength = maxLength - lengths.length + 1;
- if (availableLength > 0 && args.length === 1) {
- if (availableLength >= args[0].length) {
- return args;
- } else if (availableLength > 3) {
- return ["..." + args[0].slice(-availableLength + 3)];
- } else {
- return [args[0].slice(-availableLength)];
- }
- }
-
- if (availableLength < arraySum(lengths.map(i => Math.min(i, 6)))) {
-
- if (args.length > 1)
- return truncateArgs(args.slice(0, args.length - 1), maxLength);
- return [];
- }
- let currentLength = arraySum(lengths);
-
- if (currentLength <= availableLength) return args;
-
- while (currentLength > availableLength) {
- const maxLength = Math.max(...lengths);
- const shorterItems = lengths.filter(l => l !== maxLength);
- const nextToMaxLength =
- shorterItems.length > 0 ? Math.max(...shorterItems) : 0;
- const maxReduce = maxLength - nextToMaxLength;
- let maxItems = lengths.length - shorterItems.length;
- let overrun = currentLength - availableLength;
- for (let i = 0; i < lengths.length; i++) {
- if (lengths[i] === maxLength) {
- const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce);
- lengths[i] -= reduce;
- currentLength -= reduce;
- overrun -= reduce;
- maxItems--;
- }
- }
- }
-
- return args.map((a, i) => {
- const str = `${a}`;
- const length = lengths[i];
- if (str.length === length) {
- return str;
- } else if (length > 5) {
- return "..." + str.slice(-length + 3);
- } else if (length > 0) {
- return str.slice(-length);
- } else {
- return "";
- }
- });
- };
- module.exports = truncateArgs;
|