|
| 1 | +import { Observable } from '../Observable'; |
| 2 | +import { FindValueOperator } from '../operators/find'; |
| 3 | +import { OperatorFunction } from '../interfaces'; |
| 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 | + * <img src="./img/findIndex.png" width="100%"> |
| 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 <caption>Emit the index of first click that happens on a DIV element</caption> |
| 20 | + * var clicks = Rx.Observable.fromEvent(document, 'click'); |
| 21 | + * var result = clicks.findIndex(ev => ev.target.tagName === 'DIV'); |
| 22 | + * result.subscribe(x => console.log(x)); |
| 23 | + * |
| 24 | + * @see {@link filter} |
| 25 | + * @see {@link find} |
| 26 | + * @see {@link first} |
| 27 | + * @see {@link take} |
| 28 | + * |
| 29 | + * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate |
| 30 | + * A function called with each item to test for condition matching. |
| 31 | + * @param {any} [thisArg] An optional argument to determine the value of `this` |
| 32 | + * in the `predicate` function. |
| 33 | + * @return {Observable} An Observable of the index of the first item that |
| 34 | + * matches the condition. |
| 35 | + * @method find |
| 36 | + * @owner Observable |
| 37 | + */ |
| 38 | +export function findIndex<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean, |
| 39 | + thisArg?: any): OperatorFunction<T, number> { |
| 40 | + return (source: Observable<T>) => source.lift(new FindValueOperator(predicate, source, true, thisArg)) as Observable<any>; |
| 41 | +} |
0 commit comments