|
1 |
| -import {equal as defaultEqual} from "@softwareventures/ordered"; |
| 1 | +import type {Comparator} from "@softwareventures/ordered"; |
| 2 | +import {compare as defaultCompare, equal as defaultEqual} from "@softwareventures/ordered"; |
2 | 3 | import type {AsyncIterableLike} from "@softwareventures/async-iterable";
|
3 | 4 | import {asyncIterable} from "@softwareventures/async-iterable";
|
4 | 5 | import {hasProperty} from "unknown";
|
@@ -801,3 +802,49 @@ export function asyncFindOnceFn<T>(
|
801 | 802 | ): (iterator: AsyncIteratorLike<T>) => Promise<T | null> {
|
802 | 803 | return async iterator => asyncFindOnce(iterator, predicate);
|
803 | 804 | }
|
| 805 | + |
| 806 | +export async function asyncMaximumOnce<T extends string | number | boolean>( |
| 807 | + iterator: AsyncIteratorLike<T> |
| 808 | +): Promise<T | null>; |
| 809 | +export async function asyncMaximumOnce<T>( |
| 810 | + iterator: AsyncIteratorLike<T>, |
| 811 | + compare: Comparator<T> |
| 812 | +): Promise<T | null>; |
| 813 | +export async function asyncMaximumOnce<T>( |
| 814 | + iterator: AsyncIteratorLike<T>, |
| 815 | + compare?: Comparator<T> |
| 816 | +): Promise<T | null> { |
| 817 | + return internalAsyncMaximumOnce( |
| 818 | + iterator, |
| 819 | + compare ?? (defaultCompare as unknown as Comparator<T>) |
| 820 | + ); |
| 821 | +} |
| 822 | + |
| 823 | +export function asyncMaximumOnceFn<T>( |
| 824 | + compare: Comparator<T> |
| 825 | +): (iterator: AsyncIteratorLike<T>) => Promise<T | null> { |
| 826 | + return async iterator => internalAsyncMaximumOnce(iterator, compare); |
| 827 | +} |
| 828 | + |
| 829 | +async function internalAsyncMaximumOnce<T>( |
| 830 | + iterator: AsyncIteratorLike<T>, |
| 831 | + compare: Comparator<T> |
| 832 | +): Promise<T | null> { |
| 833 | + const it = asyncIterator(iterator); |
| 834 | + let element = await it.next(); |
| 835 | + |
| 836 | + if (element.done === true) { |
| 837 | + return null; |
| 838 | + } |
| 839 | + |
| 840 | + let max = element.value; |
| 841 | + element = await it.next(); |
| 842 | + while (element.done !== true) { |
| 843 | + if (compare(element.value, max) > 0) { |
| 844 | + max = element.value; |
| 845 | + } |
| 846 | + element = await it.next(); |
| 847 | + } |
| 848 | + |
| 849 | + return max; |
| 850 | +} |
0 commit comments