Skip to content

Commit 6a02be4

Browse files
committed
Add joinAtMost utility function
1 parent d5b3d42 commit 6a02be4

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/util.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,3 +539,27 @@ test("checkDiskUsage succeeds and produces positive numbers", async (t) => {
539539
t.true(diskUsage.numTotalBytes > 0);
540540
}
541541
});
542+
543+
test("joinAtMost - behaves like join if limit is <= 0", (t) => {
544+
const sep = ", ";
545+
const array: string[] = new Array(10).fill("test");
546+
t.is(util.joinAtMost(array, sep, 0), array.join(sep));
547+
t.is(util.joinAtMost(array, sep, -1), array.join(sep));
548+
});
549+
550+
test("joinAtMost - behaves like join if limit is >= the size of the array", (t) => {
551+
const sep = ", ";
552+
const array: string[] = new Array(10).fill("test");
553+
t.is(util.joinAtMost(array, sep, 10), array.join(sep));
554+
t.is(util.joinAtMost(array, sep, 11), array.join(sep));
555+
});
556+
557+
test("joinAtMost - truncates list if array is > than limit", (t) => {
558+
const sep = ", ";
559+
const array: string[] = Array.from(new Array(10), (_, i) => `test${i + 1}`);
560+
const result = util.joinAtMost(array, sep, 5);
561+
t.not(result, array.join(sep));
562+
t.assert(result.endsWith(", ..."));
563+
t.assert(result.includes("test5"));
564+
t.false(result.includes("test6"));
565+
});

src/util.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1270,3 +1270,25 @@ export enum CleanupLevel {
12701270
Clear = "clear",
12711271
Overlay = "overlay",
12721272
}
1273+
1274+
/**
1275+
* Like `join`, but limits the number of elements that are joined together to `limit`
1276+
* and appends `...` if the limit is exceeded.
1277+
*
1278+
* @param array The array to join.
1279+
* @param separator The separator to join the array with.
1280+
* @param limit The maximum number of elements from `array` to join.
1281+
* @returns The result of joining at most `limit`-many elements from `array`.
1282+
*/
1283+
export function joinAtMost(
1284+
array: string[],
1285+
separator: string,
1286+
limit: number,
1287+
): string {
1288+
if (limit > 0 && array.length > limit) {
1289+
array = array.slice(0, limit);
1290+
array.push("...");
1291+
}
1292+
1293+
return array.join(separator);
1294+
}

0 commit comments

Comments
 (0)