/
find-index.ts
51 lines (49 loc) · 1.53 KB
/
find-index.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
/**
* @packageDocumentation
* @module Array
*/
import { OperatorFunction } from 'rxjs';
import { map } from 'rxjs/operators';
import { PredicateFn } from '../types/generic-methods';
/**
* Returns an Observable number which is the index of the first value found in an array using Array.findIndex
* When working with data, if the array contains numbers `0` will be returned as a value to the [[PredicateFn]], but all
* other falsy values will be ignored
*
* @category Query
*
* @typeParam T Item type contained in the Array or Set
*
* @param predicate Optional [[PredicateFn]] used to get a truthy or falsy value of array values
*
* @example
* Returns the index of the first value that is `> 2`
* ```ts
* const input = [1, 2, 3, 4, 5]
* of(input).pipe(findIndex(v => v > 2)).subscribe();
* ```
* Output: `2`
*
* @example
* Returns the index of the first string where the length `< 5`
* ```ts
* const input = ['Hello', 'RxJS', 'Ninja'];
* of(input).pipe(findIndex(v => v.length < 5)).subscribe();
* ```
* Output: `1`
*
* @returns An Observable that emits a number value, the index of first value where [[PredicateFn]] is true
*/
export function findIndex<T extends unknown>(predicate?: PredicateFn<T>): OperatorFunction<Iterable<T>, number> {
return (source) =>
source.pipe(
map((value) =>
[...value].findIndex((v) => {
if (predicate && typeof v === 'number') {
return predicate(v);
}
return predicate ? Boolean(v) && predicate(v) : Boolean(v);
}),
),
);
}