Last active
January 6, 2016 20:00
-
-
Save mrbobbybryant/a438f49bd5699581bc12 to your computer and use it in GitHub Desktop.
Javascript type checking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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