-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
77 lines (69 loc) · 2.09 KB
/
index.mjs
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
67
68
69
70
71
72
73
74
75
76
77
if (!Symbol.asyncIterator) {
Symbol.asyncIterator = Symbol("Symbol.asyncIterator");
}
/**
* Checks if the given object is an Iterable (implemented `@@iterator`).
* @returns {obj is Iterable<any>}
*/
export function isIterable(obj) {
return obj !== null
&& obj !== undefined
&& typeof obj[Symbol.iterator] === "function";
}
/**
* Checks if the given object is an AsyncIterable (implemented `@@asyncIterator`).
* @returns {obj is AsyncIterable<any>}
*/
export function isAsyncIterable(obj) {
return obj !== null
&& obj !== undefined
&& typeof obj[Symbol.asyncIterator] === "function";
}
/**
* Checks if the given object is an IteratorLike (implemented `next`).
* @returns {obj is { next: Function }}
*/
export function isIteratorLike(obj) {
// An iterable object has a 'next' method, however including a 'next' method
// doesn't ensure the object is an iterator, it is only iterator-like.
return typeof obj === "object"
&& obj !== null
&& typeof obj.next === "function";
}
/**
* Checks if the given object is an IterableIterator (implemented both
* `@@iterator` and `next`).
*/
export function isIterableIterator(obj) {
return isIteratorLike(obj)
&& typeof obj[Symbol.iterator] === "function";
}
/**
* Checks if the given object is an AsyncIterableIterator (implemented
* both `@@asyncIterator` and `next`).
* @returns {obj is AsyncIterableIterator<any>}
*/
export function isAsyncIterableIterator(obj) {
return isIteratorLike(obj)
&& typeof obj[Symbol.asyncIterator] === "function";
}
/**
* Checks if the given object is a Generator.
* @returns {obj is Generator}
*/
export function isGenerator(obj) {
return isIterableIterator(obj)
&& hasGeneratorSpecials(obj);
}
/**
* Checks if the given object is an AsyncGenerator.
* @returns {obj is AsyncGenerator}
*/
export function isAsyncGenerator(obj) {
return isAsyncIterableIterator(obj)
&& hasGeneratorSpecials(obj);
}
function hasGeneratorSpecials(obj) {
return typeof obj.return === "function"
&& typeof obj.throw === "function";
}