From eb4e8884d94b7d01947e62ef5ea833f4dfb1a3f5 Mon Sep 17 00:00:00 2001 From: Wei Lu Date: Tue, 7 Oct 2014 00:08:18 -0700 Subject: [PATCH 1/2] loose instanceof: check constructor function name instead --- src/types.js | 2 +- test/types.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/types.js b/src/types.js index ddbf13d..501934f 100644 --- a/src/types.js +++ b/src/types.js @@ -26,7 +26,7 @@ module.exports = function enforce(type, value) { } default: { - if (value instanceof type) return + if (value.constructor.toString().match(/function (.*?)\(/)[1] === type.name) return } } diff --git a/test/types.js b/test/types.js index 4b6c123..fe1d149 100644 --- a/test/types.js +++ b/test/types.js @@ -1,7 +1,7 @@ var assert = require('assert') var enforceType = require('../src/types') -function CustomType() {} +function CustomType() { return "ensure non-greedy match".toUpperCase() } var types = ['Array', 'Boolean', 'Buffer', 'Number', 'String', CustomType] var values = [[], true, new Buffer(1), 1234, 'foobar', new CustomType()] From b55b10c6b69117ae9ad1a87a06767cbee99eb5a3 Mon Sep 17 00:00:00 2001 From: Wei Lu Date: Wed, 8 Oct 2014 09:26:45 -0700 Subject: [PATCH 2/2] types: replace Function.name with an IE compatible alternative --- src/types.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/types.js b/src/types.js index 501934f..5f885d0 100644 --- a/src/types.js +++ b/src/types.js @@ -26,9 +26,15 @@ module.exports = function enforce(type, value) { } default: { - if (value.constructor.toString().match(/function (.*?)\(/)[1] === type.name) return + if (getName(value.constructor) === getName(type)) return } } - throw new TypeError('Expected ' + (type.name || type) + ', got ' + value) + throw new TypeError('Expected ' + (getName(type) || type) + ', got ' + value) +} + +function getName(fn) { + // Why not fn.name: https://kangax.github.io/compat-table/es6/#function_name_property + var match = fn.toString().match(/function (.*?)\(/) + return match ? match[1] : null }