Created
November 2, 2015 19:01
-
-
Save postpostscript/76502cb3c637d202f04b to your computer and use it in GitHub Desktop.
JavaScript typed arguments
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
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 |
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
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