Debian Codegraph @

node/rxjs/src/internal/operators/distinctUntilKeyChanged.ts

raw
1 import { distinctUntilChanged } from './distinctUntilChanged';
2 import { MonoTypeOperatorFunction } from '../types';
3
4 export function distinctUntilKeyChanged<T>(key: keyof T): MonoTypeOperatorFunction<T>;
5 export function distinctUntilKeyChanged<T, K extends keyof T>(key: K, compare: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction<T>;
6
7 /**
8 * Returns an Observable that emits all items emitted by the source Observable that
9 * are distinct by comparison from the previous item, using a property accessed by
10 * using the key provided to check if the two items are distinct.
11 *
12 * If a comparator function is provided, then it will be called for each item to
13 * test for whether that value should be emitted or not.
14 *
15 * If a comparator function is not provided, an equality check is used by default.
16 *
17 * ## Examples
18 *
19 * An example comparing the name of persons
20 *
21 * ```ts
22 * import { of, distinctUntilKeyChanged } from 'rxjs';
23 *
24 * of(
25 * { age: 4, name: 'Foo' },
26 * { age: 7, name: 'Bar' },
27 * { age: 5, name: 'Foo' },
28 * { age: 6, name: 'Foo' }
29 * ).pipe(
30 * distinctUntilKeyChanged('name')
31 * )
32 * .subscribe(x => console.log(x));
33 *
34 * // displays:
35 * // { age: 4, name: 'Foo' }
36 * // { age: 7, name: 'Bar' }
37 * // { age: 5, name: 'Foo' }
38 * ```
39 *
40 * An example comparing the first letters of the name
41 *
42 * ```ts
43 * import { of, distinctUntilKeyChanged } from 'rxjs';
44 *
45 * of(
46 * { age: 4, name: 'Foo1' },
47 * { age: 7, name: 'Bar' },
48 * { age: 5, name: 'Foo2' },
49 * { age: 6, name: 'Foo3' }
50 * ).pipe(
51 * distinctUntilKeyChanged('name', (x, y) => x.substring(0, 3) === y.substring(0, 3))
52 * )
53 * .subscribe(x => console.log(x));
54 *
55 * // displays:
56 * // { age: 4, name: 'Foo1' }
57 * // { age: 7, name: 'Bar' }
58 * // { age: 5, name: 'Foo2' }
59 * ```
60 *
61 * @see {@link distinct}
62 * @see {@link distinctUntilChanged}
63 *
64 * @param key String key for object property lookup on each item.
65 * @param compare Optional comparison function called to test if an item is distinct
66 * from the previous item in the source.
67 * @return A function that returns an Observable that emits items from the source
68 * Observable with distinct values based on the key specified.
69 */
70 export function distinctUntilKeyChanged<T, K extends keyof T>(
71 key: K,
72 compare?: (x: T[K], y: T[K]) => boolean
73 ): MonoTypeOperatorFunction<T> {
74 return distinctUntilChanged((x: T, y: T) => (compare ? compare(x[key], y[key]) : x[key] === y[key]));
75 }