Merge pull request #289 from weilu/loose-instanceof

loose instanceof: check constructor function name instead
This commit is contained in:
Daniel Cousens 2014-10-13 12:07:31 +11:00
commit 7e897a5105
2 changed files with 9 additions and 3 deletions

View file

@ -26,9 +26,15 @@ module.exports = function enforce(type, value) {
} }
default: { default: {
if (value instanceof type) 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
} }

View file

@ -1,7 +1,7 @@
var assert = require('assert') var assert = require('assert')
var enforceType = require('../src/types') var enforceType = require('../src/types')
function CustomType() {} function CustomType() { return "ensure non-greedy match".toUpperCase() }
var types = ['Array', 'Boolean', 'Buffer', 'Number', 'String', CustomType] var types = ['Array', 'Boolean', 'Buffer', 'Number', 'String', CustomType]
var values = [[], true, new Buffer(1), 1234, 'foobar', new CustomType()] var values = [[], true, new Buffer(1), 1234, 'foobar', new CustomType()]