Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Checks the type of the specified value.
- *
- * @example checkType(Number, 4)
- * @example checkType(String, 'hi')
- * @example checkType(String, 4) // throws
- * @example checkType({ // custom checker
- * checkType (value, checkType) {
- * checkType(Number, value)
- * }
- * }, 4)
- */
- function checkType (type, value) {
- if (type === String && (typeof value !== 'string' || !(value instanceof String))) {
- throw new Error('Expected string.')
- } else if (type === Number && (typeof value !== 'number' || !(value instanceof Number))) {
- throw new Error('Expected number')
- } else if (type === Boolean && (typeof value !== 'boolean' || !(value instanceof Boolean))) {
- throw new Error('Expected boolean.')
- } else if (type === Date && !(value instanceof Date)) {
- throw new Error('Expected Date.')
- } else if (type === RegExp && !(value instanceof RegExp)) {
- throw new Error('Expected RegExp.')
- } else if (typeof type.checkType === 'function') {
- type.checkType(value, checkType)
- } else if (!(value instanceof type)) {
- throw new Error('Expected ' + type.name + '.')
- }
- }
Add Comment
Please, Sign In to add comment