1 | import { Observable } from '../Observable';
|
---|
2 | import { FindValueOperator } from '../operators/find';
|
---|
3 | import { OperatorFunction } from '../types';
|
---|
4 | /**
|
---|
5 | * Emits only the index of the first value emitted by the source Observable that
|
---|
6 | * meets some condition.
|
---|
7 | *
|
---|
8 | * <span class="informal">It's like {@link find}, but emits the index of the
|
---|
9 | * found value, not the value itself.</span>
|
---|
10 | *
|
---|
11 | * ![](findIndex.png)
|
---|
12 | *
|
---|
13 | * `findIndex` searches for the first item in the source Observable that matches
|
---|
14 | * the specified condition embodied by the `predicate`, and returns the
|
---|
15 | * (zero-based) index of the first occurrence in the source. Unlike
|
---|
16 | * {@link first}, the `predicate` is required in `findIndex`, and does not emit
|
---|
17 | * an error if a valid value is not found.
|
---|
18 | *
|
---|
19 | * ## Example
|
---|
20 | * Emit the index of first click that happens on a DIV element
|
---|
21 | * ```ts
|
---|
22 | * import { fromEvent } from 'rxjs';
|
---|
23 | * import { findIndex } from 'rxjs/operators';
|
---|
24 | *
|
---|
25 | * const clicks = fromEvent(document, 'click');
|
---|
26 | * const result = clicks.pipe(findIndex(ev => ev.target.tagName === 'DIV'));
|
---|
27 | * result.subscribe(x => console.log(x));
|
---|
28 | * ```
|
---|
29 | *
|
---|
30 | * @see {@link filter}
|
---|
31 | * @see {@link find}
|
---|
32 | * @see {@link first}
|
---|
33 | * @see {@link take}
|
---|
34 | *
|
---|
35 | * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate
|
---|
36 | * A function called with each item to test for condition matching.
|
---|
37 | * @param {any} [thisArg] An optional argument to determine the value of `this`
|
---|
38 | * in the `predicate` function.
|
---|
39 | * @return {Observable} An Observable of the index of the first item that
|
---|
40 | * matches the condition.
|
---|
41 | * @method find
|
---|
42 | * @owner Observable
|
---|
43 | */
|
---|
44 | export function findIndex<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,
|
---|
45 | thisArg?: any): OperatorFunction<T, number> {
|
---|
46 | return (source: Observable<T>) => source.lift(new FindValueOperator(predicate, source, true, thisArg)) as Observable<any>;
|
---|
47 | }
|
---|