Skip to content

Commit a758b0f

Browse files
committed
feat(split): add split function
1 parent 1b4d93a commit a758b0f

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
@@ -46,6 +46,7 @@ import {
4646
scanRight,
4747
scanRight1,
4848
slice,
49+
split,
4950
sum,
5051
tail,
5152
takeWhile
@@ -337,6 +338,15 @@ interface Error {
337338
type: "error";
338339
}
339340

341+
test("split", t => {
342+
t.deepEqual(split([2, 1, 3, 4, 5, 6], 2), [
343+
[2, 1],
344+
[3, 4, 5, 6]
345+
]);
346+
t.deepEqual(split([2, 1, 3, 4, 5, 6], 0), [[], [2, 1, 3, 4, 5, 6]]);
347+
t.deepEqual(split([2, 1, 3, 4, 5, 6], 10), [[2, 1, 3, 4, 5, 6], []]);
348+
});
349+
340350
function isSuccess<T>(result: Result<T>): result is Success<T> {
341351
return result.type === "success";
342352
}

index.ts

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

701+
/** Splits the array at the specified index.
702+
*
703+
* Returns a tuple where the first element is the first `index` elements of the
704+
* array, and the second element is the remaining elements of the array. */
705+
export function split<T>(array: readonly T[], index: number): [T[], T[]] {
706+
return [take(array, index), drop(array, index)];
707+
}
708+
709+
/** Returns a function that splits an array at the specified index.
710+
*
711+
* This is the curried form of {@link split}. */
712+
export function splitFn<T>(index: number): (array: readonly T[]) => [T[], T[]] {
713+
return array => split(array, index);
714+
}
715+
701716
export function partition<T, U extends T>(
702717
array: ArrayLike<T>,
703718
predicate: (element: T) => element is U

0 commit comments

Comments
 (0)