Merge pull request #289 from weilu/loose-instanceof
loose instanceof: check constructor function name instead
This commit is contained in:
commit
7e897a5105
2 changed files with 9 additions and 3 deletions
10
src/types.js
10
src/types.js
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
|
@ -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()]
|
||||||
|
|
Loading…
Reference in a new issue