diff --git a/index.js b/index.js index befda91..02036be 100644 --- a/index.js +++ b/index.js @@ -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'); diff --git a/readme.md b/readme.md index 0962385..be284c4 100644 --- a/readme.md +++ b/readme.md @@ -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) diff --git a/test.js b/test.js index 316bb41..89b4a41 100644 --- a/test.js +++ b/test.js @@ -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'); });