Browse Source

Merge pull request #289 from weilu/loose-instanceof

loose instanceof: check constructor function name instead
hk-custom-address
Daniel Cousens 10 years ago
parent
commit
7e897a5105
  1. 10
      src/types.js
  2. 2
      test/types.js

10
src/types.js

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

2
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()]

Loading…
Cancel
Save