Skip to content

Instantly share code, notes, and snippets.

@espretto
Last active August 29, 2015 14:21
Show Gist options
  • Save espretto/94e7de974ff672fc36c6 to your computer and use it in GitHub Desktop.
Save espretto/94e7de974ff672fc36c6 to your computer and use it in GitHub Desktop.
JavaScript: typr - deep type checking with error reports
/**
* typr - deep type checking with error reports
* MIT licence
*/
;(function (root) {
'use strict';
/* ---------------------------------------------------------------------------
* setup
*/
var objectToString = Object.prototype.toString;
function forOwn (object, fn) {
Object.keys(object).forEach(function (key) {
return fn(object[key], key, object);
});
}
/* ---------------------------------------------------------------------------
* main
*/
function type (any) {
var type = typeof any;
return (
any === null ? 'null' :
// avoid webkit bug where `typeof /re/` yields 'function'
type !== 'object' && type !== 'function' ? type :
objectToString.call(any).slice(8, -1).toLowerCase()
);
}
function matchesByType (any, expectedType) {
return (function matchesByType_ (any, expectedType, errors, keychain){
var metaType = type(expectedType),
result;
switch (metaType) {
case 'string':
result = type(any) === expectedType;
break;
case 'array':
result = expectedType.reduce(function (result, expectedType, index) {
return (result && matchesByType_(any[index], expectedType, errors, keychain.concat(i));
}, type(any) === metaType);
break;
// case 'date':
// case 'object':
// case 'regexp':
// case 'function':
default:
var result = type(any) === metaType;
if (result) {
forOwn(expectedType, function (expectedType, key) {
return (result = result && matchesByType_(any[key], expectedType, errors, keychain.concat(key));
});
}
}
if (!result) errors.push(keychain);
return errors;
}(any, expectedType, [], []));
}
/* ---------------------------------------------------------------------------
* export
*/
root.typr = {
type: type,
matchesByType: matchesByType
};
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment