Add is.generator() and is.generatorFunction() (#4)

This commit is contained in:
Kunall Banerjee 2017-09-28 23:01:48 -04:00 committed by Sindre Sorhus
parent 000f66bbdc
commit dbe5cc8d82
3 changed files with 26 additions and 1 deletions

View file

@ -82,6 +82,11 @@ const hasPromiseAPI = x =>
is.promise = x => is.nativePromise(x) || hasPromiseAPI(x);
is.generator = x => is.iterable(x) && is.function(x.next) && is.function(x.throw);
// Change to use `isObjectOfType` once Node 4.x.x LTS is dropped
is.generatorFunction = x => x.constructor.name === 'GeneratorFunction';
is.regExp = isObjectOfType('RegExp');
is.date = isObjectOfType('Date');
is.error = isObjectOfType('Error');

View file

@ -78,6 +78,12 @@ Keep in mind that [functions are objects too](https://developer.mozilla.org/en-U
Returns `true` for any object with a `.then()` and `.catch()` method. Prefer this one over `.nativePromise()` as you usually want to allow userland promise implementations too.
##### .generator(value)
Returns `true` for any object that implements its own `.next()` and `.throw()` methods and has a function definition for `Symbol.iterator`.
##### .generatorFunction(value)
##### .map(value)
##### .set(value)
##### .weakMap(value)

16
test.js
View file

@ -58,6 +58,9 @@ const types = new Map([
PromiseSubclassFixture.resolve()
]],
['promise', {then() {}, catch() {}}],
['generator', (function * () {
yield 42;
})()],
['map', new Map()],
['set', new Set()],
['weakMap', new WeakMap()],
@ -86,7 +89,7 @@ const types = new Map([
['integer', 6]
]);
// This ensure a certain method matches only the types
// This ensures a certain method matches only the types
// it's supposed to and none of the other methods' types
const testType = (t, type, exclude) => {
for (const [key, value] of types) {
@ -170,6 +173,17 @@ if (isNode8orHigher) {
});
}
test('is.generator', t => {
testType(t, 'generator', ['function']);
});
test('is.generatorFunction', t => {
const gen = function * () {
yield 42;
};
t.true(m.generatorFunction(gen));
});
test('is.map', t => {
testType(t, 'map');
});