-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.ts
66 lines (58 loc) · 1.26 KB
/
index.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
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @packageDocumentation
*
* Return the last value from an (async)iterable.
*
* @example
*
* ```javascript
* import last from 'it-last'
*
* // This can also be an iterator, generator, etc
* const values = [0, 1, 2, 3, 4]
*
* const res = last(values)
*
* console.info(res) // 4
* ```
*
* Async sources must be awaited:
*
* ```javascript
* import last from 'it-last'
*
* const values = async function * () {
* yield * [0, 1, 2, 3, 4]
* }
*
* const res = await last(values())
*
* console.info(res) // 4
* ```
*/
function isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {
return thing[Symbol.asyncIterator] != null
}
/**
* Returns the last item of an (async) iterable, unless empty, in which case
* return `undefined`
*/
function last <T> (source: Iterable<T>): T | undefined
function last <T> (source: Iterable<T> | AsyncIterable<T>): Promise<T | undefined>
function last <T> (source: Iterable<T> | AsyncIterable<T>): Promise<T | undefined> | T | undefined {
if (isAsyncIterable(source)) {
return (async () => {
let res
for await (const entry of source) {
res = entry
}
return res
})()
}
let res
for (const entry of source) {
res = entry
}
return res
}
export default last