Skip to content

Instantly share code, notes, and snippets.

@mrbobbybryant
Last active January 6, 2016 20:00
Show Gist options
  • Save mrbobbybryant/a438f49bd5699581bc12 to your computer and use it in GitHub Desktop.
Save mrbobbybryant/a438f49bd5699581bc12 to your computer and use it in GitHub Desktop.
Javascript type checking
var typeOf = function( type ) {
return function( value ) {
if ( typeof value !== type ) {
throw new TypeError( 'Expected a ' + type + '!' );
} else {
return value;
}
};
};
var num = typeOf( 'number' );
var bool = typeOf( 'boolean' );
var str = typeOf( 'string' );
var func = typeOf( 'function' );
var undef = typeOf( 'undefined' );
var obj = typeOf( 'object' );
console.log(num(3)); // 3
console.log(num("3")); //Error: Expected a Number.
var is_array = function(arr) {
if ( {}.toString.call(arr) !== '[object Array]' ) {
throw new TypeError( 'Expected an Array!' );
} else {
return arr;
}
};
console.log(is_array([1,2,3])); //[1,2,3]
console.log(is_array(4); //Error: Expected an Array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment