From b6f54d338df03f8772bb0270bad8381cff4fe9ed Mon Sep 17 00:00:00 2001 From: stoeffel Date: Wed, 11 Feb 2015 16:08:00 +0100 Subject: [PATCH] add is-regexp function and tests --- README.md | 10 ++++++++++ is-regexp.js | 18 ++++++++++++++++++ pick.js | 5 +---- test/test-isregexp.js | 30 ++++++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 is-regexp.js create mode 100644 test/test-isregexp.js diff --git a/README.md b/README.md index 8e468a2..a41bbd3 100644 --- a/README.md +++ b/README.md @@ -294,6 +294,16 @@ var isObject = require('101/is-object'); [{}, { foo: 1 }, 100].map(isObject); // [true, true, false] ``` +## isRegExp + +Check if a value is an instance of RegExp + +```js +var isRegExp = require('101/is-regexp'); + +[new RegExp('.*'), /.*/, {}, 1].map(isRegExp); // [true, true, false, false] +``` + ## isString Functional version of val typeof 'string' diff --git a/is-regexp.js b/is-regexp.js new file mode 100644 index 0000000..cabbdad --- /dev/null +++ b/is-regexp.js @@ -0,0 +1,18 @@ +/** + * @module 101/is-regexp + */ + +/** + * Check if a value is an instance of RegExp + * @function module:101/is-regexp + * @param {*} val - value checked to be an instance of RegExp + * @return {boolean} Whether the value is an object or not + */ +var exists = require('./exists'); + +module.exports = function isRegExp (val) { + return typeof val === 'object' && + exists(val) && + Object.prototype.toString.call(val) == '[object RegExp]'; +}; + diff --git a/pick.js b/pick.js index 9e06e27..82d271a 100644 --- a/pick.js +++ b/pick.js @@ -3,6 +3,7 @@ */ var isObject = require('./is-object'); +var isRegExp = require('./is-regexp'); /** * Returns a new object with the specified keys (with key values from obj). @@ -50,7 +51,3 @@ function copy (from, to) { } }; } - -function isRegExp (obj) { - return Object.prototype.toString.call(obj) == '[object RegExp]'; -} diff --git a/test/test-isregexp.js b/test/test-isregexp.js new file mode 100644 index 0000000..9110c05 --- /dev/null +++ b/test/test-isregexp.js @@ -0,0 +1,30 @@ +var Lab = require('lab'); +var lab = exports.lab = Lab.script(); + +var describe = lab.describe; +var it = lab.it; +var expect = Lab.expect; + +var isRegExp = require('../is-regexp'); + +describe('isRegExp', function () { + it('should return true for instance of RegExp', function(done) { + var regexp = new RegExp('.*'); + expect(isRegExp(regexp)).to.be.true; + expect(isRegExp(/.*/)).to.be.true; + done(); + }); + + it('should return false for non-regexp', function(done) { + expect(isRegExp({})).to.be.false; + expect(isRegExp(['foo'])).to.be.false; + expect(isRegExp('foo')).to.be.false; + expect(isRegExp(101)).to.be.false; + expect(isRegExp(function () {})).to.be.false; + expect(isRegExp(null)).to.be.false; + expect(isRegExp(undefined)).to.be.false; + expect(isRegExp(new String('hey'))).to.be.false; + expect(isRegExp(new Number(101))).to.be.false; + done(); + }); +});