Skip to content

Instantly share code, notes, and snippets.

@postpostscript
Created November 2, 2015 19:01
Show Gist options
  • Save postpostscript/76502cb3c637d202f04b to your computer and use it in GitHub Desktop.
Save postpostscript/76502cb3c637d202f04b to your computer and use it in GitHub Desktop.
JavaScript typed arguments
function typedArgument(type, value, defaultValue) {
return (typeof value !== 'undefined' && typeof value !== 'null' && ((typeof type === 'function' && value.constructor === type) || (typeof type === 'string' && (!type || typeof value === type)))) ? value : defaultValue;
}
/** Example: **/
function add(a,b) {
var a = typedArgument(Number, a, 0);
var b = typedArgument('number', b, 0);
return a + b;
}
add(10, 'this is not a number') // => 10
add(10, 5) // => 15
add(10) // => 10
add() // => 0
function typedArgument(t,n,e){return"undefined"==typeof n||"null"==typeof n||("function"!=typeof t||n.constructor!==t)&&("string"!=typeof t||t&&typeof n!==t)?e:n}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment