Skip to content

Commit e930ea2

Browse files
committed
feat(partitionwhile): add partitionWhile function
1 parent 0c3cb7c commit e930ea2

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

index.test.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import test from "ava";
2-
import {filterFirst, find, findIndex, foldMap, partition} from "./index";
2+
import {filterFirst, find, findIndex, foldMap, partition, partitionWhile} from "./index";
33

44
test("filterFirst", t => {
55
t.deepEqual(filterFirst([1, 2, 3, 4, 3, 2, 1], n => n < 3), [1, 2, 4, 3, 2, 1]);
@@ -56,4 +56,24 @@ test("partition", t => {
5656
], [
5757
{type: "error"}
5858
]]);
59+
});
60+
61+
test("partitionWhile", t => {
62+
t.deepEqual(partitionWhile(["abc", "def", "ghi"], (_: string, i: number) => (i % 2 === 0)),
63+
[["abc"], ["def", "ghi"]]);
64+
65+
const results: Array<Result<string>> = [
66+
{type: "success", value: "hello"},
67+
{type: "error"},
68+
{type: "success", value: "goodbye"}
69+
];
70+
71+
const partitionedResults: [Array<Success<string>>, Array<Result<string>>] = partitionWhile(results, isSuccess);
72+
73+
t.deepEqual(partitionedResults, [[
74+
{type: "success", value: "hello"}
75+
], [
76+
{type: "error"},
77+
{type: "success", value: "goodbye"}
78+
]]);
5979
});

index.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,27 @@ export function partitionFn<T>(predicate: (element: T, index: number) => boolean
465465
return array => partition(array, predicate);
466466
}
467467

468+
export function partitionWhile<T, U extends T>(array: ArrayLike<T>,
469+
predicate: (element: T) => element is U): [U[], T[]];
470+
export function partitionWhile<T>(array: ArrayLike<T>, predicate: (element: T, index: number) => boolean): [T[], T[]];
471+
export function partitionWhile<T>(array: ArrayLike<T>, predicate: (element: T, index: number) => boolean): [T[], T[]] {
472+
let i;
473+
for (i = 0; i < array.length; ++i) {
474+
if (!predicate(array[i], i)) {
475+
break;
476+
}
477+
}
478+
479+
return [take(array, i), drop(array, i)];
480+
}
481+
482+
export function partitionWhileFn<T, U extends T>(
483+
predicate: (element: T) => element is U): (array: ReadonlyArray<T>) => [U[], T[]];
484+
export function partitionWhileFn<T>(predicate: (element: T) => boolean): (array: ReadonlyArray<T>) => [T[], T[]];
485+
export function partitionWhileFn<T>(predicate: (element: T) => boolean): (array: ReadonlyArray<T>) => [T[], T[]] {
486+
return array => partitionWhile(array, predicate);
487+
}
488+
468489
export function keyBy<TElement, TKey extends Key>(
469490
array: ArrayLike<TElement>,
470491
f: (element: TElement) => TKey

0 commit comments

Comments
 (0)