Skip to content

Commit 7114bfa

Browse files
committed
feat(lastIndexOf): add lastIndexOf function
(cherry picked from commit 6013891)
1 parent 562b358 commit 7114bfa

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
@@ -552,6 +552,19 @@ export function indexOfFn<T>(value: T): (array: ArrayLike<T>) => number | null {
552552
return array => indexOf(array, value);
553553
}
554554

555+
export function lastIndexOf<T>(array: ArrayLike<T>, value: T): number | null {
556+
for (let i = array.length - 1; i >= 0; --i) {
557+
if (array[i] === value) {
558+
return i;
559+
}
560+
}
561+
return null;
562+
}
563+
564+
export function lastIndexOfFn<T>(value: T): (array: ArrayLike<T>) => number | null {
565+
return array => lastIndexOf(array, value);
566+
}
567+
555568
export function findIndex<T>(
556569
array: ArrayLike<T>,
557570
predicate: (element: T, index: number) => boolean

0 commit comments

Comments
 (0)