Skip to content

Commit

Permalink
add findLastIndex for array
Browse files Browse the repository at this point in the history
  • Loading branch information
smaillz authored and meskill committed Jun 19, 2023
1 parent 4b50f64 commit a655a7a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/array/__tests__/findLastIndex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import findLastIndex from '../findLastIndex';

describe('utils/array/findLastIndex', () => {
it('should return founded value or undefined otherwise', () => {
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];

expect(findLastIndex((a) => a > 3, arr)).toBe(5);
expect(findLastIndex((a) => a > 100, arr)).toBe(-1);
expect(findLastIndex<number>((a) => a % 2 === 0)(arr)).toBe(7);
});

it('test callback parameters', () => {
const fn = jest.fn();
const arr = [1, 2, 3];

findLastIndex(fn, arr);

expect(fn).toHaveBeenCalledWith(3, 2, arr);
expect(fn).toHaveBeenCalledWith(2, 1, arr);
expect(fn).toHaveBeenCalledWith(1, 0, arr);
});
});
31 changes: 31 additions & 0 deletions src/array/findLastIndex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import curryN from '../function/curryN';
import { ArrPred } from '../typings/types';

interface FindLastIndex {
<T>(fn: ArrPred<T>, list: ArrayLike<T>): number;
<T>(fn: ArrPred<T>): (list: ArrayLike<T>) => number;
}

/**
* Returns the index of the last element of the list which matches the
* predicate, or `-1` if no element matches.
*
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} arr The array to consider.
* @return {Number} The index of the element found, or `-1`.
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}, {a: 2}, {a: 1}];
* findLastIndex(x => x.a === 2)(xs); //=> 3
* findLastIndex(x => x.a === 4)(xs); //=> -1
*/
export default curryN(2, <T>(fn: ArrPred<T>, arr: ArrayLike<T> = []) => {
for (let i = arr.length - 1; i >= 0; i--) {
if (fn(arr[i], i, arr)) {
return i;
}
}

return -1;
}) as FindLastIndex;

0 comments on commit a655a7a

Please sign in to comment.