Skip to content

Commit

Permalink
feat(findLast): add findLast function
Browse files Browse the repository at this point in the history
(cherry picked from commit f75f89e)
  • Loading branch information
djcsdy committed Dec 5, 2023
1 parent c69fe93 commit 656352a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
8 changes: 8 additions & 0 deletions index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
filterFirst,
find,
findIndex,
findLast,
findLastIndex,
first,
fold,
Expand Down Expand Up @@ -299,6 +300,13 @@ test("find", t => {
);
});

test("findLast", t => {
t.is(
findLast([1, 2, 3, 4, 5, 2, 1], n => n >= 3),
5
);
});

test("maximum", t => {
t.is(maximum([1, 2, 3]), 3);
t.is(maximum([1, 2, 3, 4, 3, 2, 1]), 4);
Expand Down
33 changes: 33 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,39 @@ export function findFn<T>(
return array => find(array, predicate);
}

export function findLast<T, U extends T>(
array: ArrayLike<T>,
predicate: (element: T) => element is U
): U | null;
export function findLast<T>(
array: ArrayLike<T>,
predicate: (element: T, index: number) => boolean
): T | null;
export function findLast<T>(
array: ArrayLike<T>,
predicate: (element: T, index: number) => boolean
): T | null {
for (let i = array.length - 1; i >= 0; --i) {
const element = array[i];
if (predicate(element, i)) {
return element;
}
}
return null;
}

export function findLastFn<T, U extends T>(
predicate: (element: T) => element is U
): (array: ArrayLike<T>) => U | null;
export function findLastFn<T>(
predicate: (element: T, index: number) => boolean
): (array: ArrayLike<T>) => T | null;
export function findLastFn<T>(
predicate: (element: T, index: number) => boolean
): (array: ArrayLike<T>) => T | null {
return array => findLast(array, predicate);
}

export function maximum<T extends string | number | boolean>(array: ArrayLike<T>): T | null;
export function maximum<T>(array: ArrayLike<T>, compare: Comparator<T>): T | null;
export function maximum<T>(
Expand Down

0 comments on commit 656352a

Please sign in to comment.