@ayonli/jsext
Version:
A JavaScript extension package for building strong and modern applications.
89 lines (80 loc) • 2.36 kB
JavaScript
if (!Symbol.asyncIterator) {
// @ts-ignore
Symbol.asyncIterator = Symbol("Symbol.asyncIterator");
}
/**
* Checks if the given object is an Iterable (implemented `@@iterator`).
* @param {any} obj
* @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`).
* @param {any} obj
* @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`).
* @param {any} obj
* @returns {obj is { [x: string | symbol]: any; 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`).
* @param {any} obj
*/
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`).
* @param {any} obj
* @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.
* @param {any} obj
* @returns {obj is Generator}
*/
export function isGenerator(obj) {
return isIterableIterator(obj)
&& hasGeneratorSpecials(obj);
}
/**
* Checks if the given object is an AsyncGenerator.
* @param {any} obj
* @returns {obj is AsyncGenerator}
*/
export function isAsyncGenerator(obj) {
return isAsyncIterableIterator(obj)
&& hasGeneratorSpecials(obj);
}
/**
* @param {any} obj
*/
function hasGeneratorSpecials(obj) {
return typeof obj.return === "function"
&& typeof obj.throw === "function";
}