Daniel Cousens
10 years ago
13 changed files with 46 additions and 113 deletions
@ -1,40 +0,0 @@ |
|||
module.exports = function enforce(type, value) { |
|||
switch (type) { |
|||
case 'Array': { |
|||
if (Array.isArray(value)) return |
|||
break |
|||
} |
|||
|
|||
case 'Boolean': { |
|||
if (typeof value === 'boolean') return |
|||
break |
|||
} |
|||
|
|||
case 'Buffer': { |
|||
if (Buffer.isBuffer(value)) return |
|||
break |
|||
} |
|||
|
|||
case 'Number': { |
|||
if (typeof value === 'number') return |
|||
break |
|||
} |
|||
|
|||
case 'String': { |
|||
if (typeof value === 'string') return |
|||
break |
|||
} |
|||
|
|||
default: { |
|||
if (getName(value.constructor) === getName(type)) return |
|||
} |
|||
} |
|||
|
|||
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,28 +0,0 @@ |
|||
var assert = require('assert') |
|||
var enforceType = require('../src/types') |
|||
|
|||
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()] |
|||
|
|||
describe('enforceType', function() { |
|||
types.forEach(function(type, i) { |
|||
describe(type, function() { |
|||
values.forEach(function(value, j) { |
|||
if (j === i) { |
|||
it('passes for ' + types[j], function() { |
|||
enforceType(type, value) |
|||
}) |
|||
|
|||
} else { |
|||
it('fails for ' + types[j], function() { |
|||
assert.throws(function() { |
|||
enforceType(type, value) |
|||
}, new RegExp('Expected ' + (type.name || type) + ', got ')) |
|||
}) |
|||
} |
|||
}) |
|||
}) |
|||
}) |
|||
}) |
Loading…
Reference in new issue