Skip to content

Commit a655a7a

Browse files
smaillzmeskill
authored andcommitted
add findLastIndex for array
1 parent 4b50f64 commit a655a7a

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import findLastIndex from '../findLastIndex';
2+
3+
describe('utils/array/findLastIndex', () => {
4+
it('should return founded value or undefined otherwise', () => {
5+
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
6+
7+
expect(findLastIndex((a) => a > 3, arr)).toBe(5);
8+
expect(findLastIndex((a) => a > 100, arr)).toBe(-1);
9+
expect(findLastIndex<number>((a) => a % 2 === 0)(arr)).toBe(7);
10+
});
11+
12+
it('test callback parameters', () => {
13+
const fn = jest.fn();
14+
const arr = [1, 2, 3];
15+
16+
findLastIndex(fn, arr);
17+
18+
expect(fn).toHaveBeenCalledWith(3, 2, arr);
19+
expect(fn).toHaveBeenCalledWith(2, 1, arr);
20+
expect(fn).toHaveBeenCalledWith(1, 0, arr);
21+
});
22+
});

src/array/findLastIndex.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import curryN from '../function/curryN';
2+
import { ArrPred } from '../typings/types';
3+
4+
interface FindLastIndex {
5+
<T>(fn: ArrPred<T>, list: ArrayLike<T>): number;
6+
<T>(fn: ArrPred<T>): (list: ArrayLike<T>) => number;
7+
}
8+
9+
/**
10+
* Returns the index of the last element of the list which matches the
11+
* predicate, or `-1` if no element matches.
12+
*
13+
* @param {Function} fn The predicate function used to determine if the element is the
14+
* desired one.
15+
* @param {Array} arr The array to consider.
16+
* @return {Number} The index of the element found, or `-1`.
17+
* @example
18+
*
19+
* var xs = [{a: 1}, {a: 2}, {a: 3}, {a: 2}, {a: 1}];
20+
* findLastIndex(x => x.a === 2)(xs); //=> 3
21+
* findLastIndex(x => x.a === 4)(xs); //=> -1
22+
*/
23+
export default curryN(2, <T>(fn: ArrPred<T>, arr: ArrayLike<T> = []) => {
24+
for (let i = arr.length - 1; i >= 0; i--) {
25+
if (fn(arr[i], i, arr)) {
26+
return i;
27+
}
28+
}
29+
30+
return -1;
31+
}) as FindLastIndex;

0 commit comments

Comments
 (0)