-
Notifications
You must be signed in to change notification settings - Fork 0
/
max.ts
53 lines (47 loc) · 1.16 KB
/
max.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import type { IterableReturnValue } from '@/types'
import { IterableTypeException, isAsyncIterable, isIterable } from '@/utils'
function sync(iterable: Iterable<number>) {
let max = NaN
for (const v of iterable) {
if (Number.isNaN(v)) {
return v
}
if (v > max || Number.isNaN(max)) {
max = v
}
}
return max
}
async function async(iterable: AsyncIterable<number>) {
let max = NaN
for await (const v of iterable) {
if (Number.isNaN(v)) {
return v
}
if (v > max || Number.isNaN(max)) {
max = v
}
}
return max
}
/**
* Return the largest item of the iterable/asyncIterable
*
* @example
* ```typescript
* console.log(max([1, 2, 3])) // 3
* ```
*
* {@link https://github.com/niuiic/fx-flow/blob/main/packages/test/src/pipe/strict/max.spec.ts | More examples}
*/
function max<A extends Iterable<number> | AsyncIterable<number>>(iterator: A): IterableReturnValue<A>
function max(iterable: Iterable<number> | AsyncIterable<number>) {
if (isIterable(iterable)) {
return sync(iterable)
}
if (isAsyncIterable(iterable)) {
return async(iterable)
}
throw new IterableTypeException()
}
export { max }