Skip to content

Commit b934e94

Browse files
committed
feat(split): add split function
(cherry picked from commit a758b0f)
1 parent d8d7e92 commit b934e94

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

index.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
scanRight,
4242
scanRight1,
4343
slice,
44+
split,
4445
sum,
4546
tail,
4647
takeWhile
@@ -332,6 +333,15 @@ interface Error {
332333
type: "error";
333334
}
334335

336+
test("split", t => {
337+
t.deepEqual(split([2, 1, 3, 4, 5, 6], 2), [
338+
[2, 1],
339+
[3, 4, 5, 6]
340+
]);
341+
t.deepEqual(split([2, 1, 3, 4, 5, 6], 0), [[], [2, 1, 3, 4, 5, 6]]);
342+
t.deepEqual(split([2, 1, 3, 4, 5, 6], 10), [[2, 1, 3, 4, 5, 6], []]);
343+
});
344+
335345
function isSuccess<T>(result: Result<T>): result is Success<T> {
336346
return result.type === "success";
337347
}

index.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -705,6 +705,21 @@ export function scanRight1Fn<T>(
705705
return array => scanRight1(array, f);
706706
}
707707

708+
/** Splits the array at the specified index.
709+
*
710+
* Returns a tuple where the first element is the first `index` elements of the
711+
* array, and the second element is the remaining elements of the array. */
712+
export function split<T>(array: readonly T[], index: number): [T[], T[]] {
713+
return [take(array, index), drop(array, index)];
714+
}
715+
716+
/** Returns a function that splits an array at the specified index.
717+
*
718+
* This is the curried form of {@link split}. */
719+
export function splitFn<T>(index: number): (array: readonly T[]) => [T[], T[]] {
720+
return array => split(array, index);
721+
}
722+
708723
export function partition<T, U extends T>(
709724
array: ArrayLike<T>,
710725
predicate: (element: T) => element is U

0 commit comments

Comments
 (0)