forked from remeda/remeda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
findLast.ts
76 lines (70 loc) · 1.86 KB
/
findLast.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { purry } from './purry';
import { Pred, PredIndexedOptional, PredIndexed } from './_types';
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param array the array
* @param fn the predicate
* @signature
* R.findLast(items, fn)
* R.findLast.indexed(items, fn)
* @example
* R.findLast([1, 3, 4, 6], n => n % 2 === 1) // => 3
* R.findLast.indexed([1, 3, 4, 6], (n, i) => n % 2 === 1) // => 3
* @data_first
* @indexed
* @pipeable
* @category Array
*/
export function findLast<T>(
array: ReadonlyArray<T>,
fn: Pred<T, boolean>
): T | undefined;
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param fn the predicate
* @signature
* R.findLast(fn)(items)
* R.findLast.indexed(fn)(items)
* @example
* R.pipe(
* [1, 3, 4, 6],
* R.findLast(n => n % 2 === 1)
* ) // => 3
* R.pipe(
* [1, 3, 4, 6],
* R.findLast.indexed((n, i) => n % 2 === 1)
* ) // => 3
* @data_last
* @indexed
* @pipeable
* @category Array
*/
export function findLast<T = never>(
fn: Pred<T, boolean>
): (array: ReadonlyArray<T>) => T | undefined;
export function findLast() {
return purry(_findLast(false), arguments);
}
const _findLast =
(indexed: boolean) =>
<T>(array: Array<T>, fn: PredIndexedOptional<T, boolean>) => {
for (let i = array.length - 1; i >= 0; i--) {
if (indexed ? fn(array[i], i, array) : fn(array[i])) {
return array[i];
}
}
};
export namespace findLast {
export function indexed<T>(
array: ReadonlyArray<T>,
fn: PredIndexed<T, boolean>
): T | undefined;
export function indexed<T>(
fn: PredIndexed<T, boolean>
): (array: ReadonlyArray<T>) => T | undefined;
export function indexed() {
return purry(_findLast(true), arguments);
}
}