-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |