Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(identity): add identity docs #6750

Merged
merged 2 commits into from Jan 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/internal/util/identity.ts
@@ -1,3 +1,45 @@
/**
* This function takes one parameter and just returns it. Simply put,
* this is like `<T>(x: T): T => x`.
*
* ## Examples
*
* This is useful in some cases when using things like `mergeMap`
*
* ```ts
* import { interval, take, map, range, mergeMap, identity } from 'rxjs';
*
* const source$ = interval(1000).pipe(take(5));
*
* const result$ = source$.pipe(
* map(i => range(i)),
* mergeMap(identity) // same as mergeMap(x => x)
* );
*
* result$.subscribe({
* next: console.log
* });
* ```
*
Copy link
Member

@benlesh benlesh Jan 11, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One of the main use cases I personally have for this is with a ternary to selectively apply an operator:

source$.pipe(
  condition ? mergeMap(doSomething) : identity
)

It would be nice to have an example of that.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll add.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added (though, as the second example). If you'd like this example to be the first one, I can swap them.

* Or when you want to selectively apply an operator
*
* ```ts
* import { interval, take, identity } from 'rxjs';
*
* const shouldLimit = () => Math.random() < 0.5;
*
* const source$ = interval(1000);
*
* const result$ = source$.pipe(shouldLimit() ? take(5) : identity);
*
* result$.subscribe({
* next: console.log
* });
* ```
*
* @param x Any value that is returned by this function
* @returns The value passed as the first parameter to this function
*/
export function identity<T>(x: T): T {
return x;
}