From 02688fa94cfda7160985bcb54bbe0140e0608972 Mon Sep 17 00:00:00 2001 From: Angus MacDonald Date: Fri, 27 Nov 2020 12:45:31 -0600 Subject: [PATCH] Add arrayf.split --- src/arrayf/arrayf.ts | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/arrayf/arrayf.ts b/src/arrayf/arrayf.ts index c53ee4696a..63d1342df3 100644 --- a/src/arrayf/arrayf.ts +++ b/src/arrayf/arrayf.ts @@ -28,5 +28,38 @@ export class arrayf { return output; } + /** + * Splits an array by a given split value. Useful when casting to string + * for splitting won't cut it, such as when dealing with objects. + * + * ``` + * const a = {}; + * const b = {}; + * const c = {}; + * arrayf.split([a,b,c], b); // Returns [[a], [c]]; + * arrayf.split([a,b,c,b,c], b); // Returns [[a], [c], [c]]; + * arrayf.split([a,b,c,b,c], b, 1); // Returns [[a], [c, b, c]]; + * ``` + */ + static split( + values: T[], + splitValue: T, + limit: number = Number.POSITIVE_INFINITY + ): T[][] { + let remainder = values; + const result = []; + + while (remainder.indexOf(splitValue) !== -1 && result.length < limit) { + const splitPosition: number = remainder.indexOf(splitValue); + const splitPiece: T[] = remainder.slice(0, splitPosition); + remainder = remainder.slice(splitPosition + 1); + result.push(splitPiece); + } -} \ No newline at end of file + if (result.length < limit) { + result.push(remainder); + } + + return result; + } +}