/
match-last.ts
48 lines (47 loc) · 1.17 KB
/
match-last.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
import type { Predicate } from "@thi.ng/api";
import { isIterable } from "@thi.ng/checks";
import type { Transducer } from "../api";
import { comp } from "../func/comp";
import { iterator } from "../iterator";
import { filter } from "./filter";
import { takeLast } from "./take-last";
/**
* Transducer composition / syntax sugar for:
*
* @example
* ```ts
* comp(filter(pred), takeLast(1))
* ```
*
* Yields none or only the last value which passed the predicate check.
* If `src` input is given, returns last match found (or `undefined`).
*
* @example
* ```ts
* matchLast((x) => x >= 5, [3, 1, 6, 5, 4, 2])
* // 5
*
* transduce(
* comp(
* matchLast((x) => x >= 5),
* map((x) => x * 10)
* ),
* last(),
* [3, 1, 4, 2, 6, 5]
* )
* // 50
* ```
*
* @param pred - predicate function
* @param src -
*/
export function matchLast<T>(pred: Predicate<T>): Transducer<T, T>;
export function matchLast<T>(
pred: Predicate<T>,
src: Iterable<T>
): T | undefined;
export function matchLast<T>(pred: Predicate<T>, src?: Iterable<T>): any {
return isIterable(src)
? [...iterator(matchLast(pred), src)][0]
: comp(filter(pred), takeLast(1));
}