Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 changes: 1 addition & 1 deletion test/types.js
Original file line number Diff line number Diff line change
@@ -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()]
Expand Down