Skip to content

Commit c69fe93

Browse files
committed
feat(lastIndexOf): add lastIndexOf function
(cherry picked from commit 6013891)
1 parent 3324194 commit c69fe93

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

index.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
keyFirstBy,
3232
keyLastBy,
3333
last,
34+
lastIndexOf,
3435
map,
3536
mapKeyBy,
3637
mapKeyFirstBy,
@@ -273,6 +274,10 @@ test("contains", t => {
273274
t.false(contains([1, 2, 3], 0));
274275
});
275276

277+
test("lastIndexOf", t => {
278+
t.is(lastIndexOf([1, 2, 3, 4, 3, 2, 1], 3), 4);
279+
});
280+
276281
test("findIndex", t => {
277282
t.is(
278283
findIndex([1, 2, 3, 4, 3, 2, 1], n => n >= 3),

index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -532,6 +532,19 @@ export function indexOfFn<T>(value: T): (array: ArrayLike<T>) => number | null {
532532
return array => indexOf(array, value);
533533
}
534534

535+
export function lastIndexOf<T>(array: ArrayLike<T>, value: T): number | null {
536+
for (let i = array.length - 1; i >= 0; --i) {
537+
if (array[i] === value) {
538+
return i;
539+
}
540+
}
541+
return null;
542+
}
543+
544+
export function lastIndexOfFn<T>(value: T): (array: ArrayLike<T>) => number | null {
545+
return array => lastIndexOf(array, value);
546+
}
547+
535548
export function findIndex<T>(
536549
array: ArrayLike<T>,
537550
predicate: (element: T, index: number) => boolean

0 commit comments

Comments
 (0)