Last active
October 7, 2015 13:18
-
-
Save casecode/21d99cbb42760d81b5a8 to your computer and use it in GitHub Desktop.
Typed Functions
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 getType(arg) { | |
return ({}).toString.call(arg).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); | |
} | |
function typeMatch(arg, type) { | |
if (typeof arg === 'number' && typeof type === 'number' && isNaN(arg) && isNaN(type)) return true; | |
if ((typeof arg === 'number' && isNaN(arg)) || (typeof type === 'number' && isNaN(type))) return false; | |
if (getType(arg) === getType(type)) return true; | |
if (type instanceof Function && arg.constructor === type) return true; | |
return false; | |
} | |
function typedFunction(paramDefs, fn) { | |
const fnParams = fn.toString().match(/\((.*?)\)/)[1].split(/,\s*/); | |
return (...args) => { | |
fnParams.map((param, idx) => { | |
if (!typeMatch(args[idx], paramDefs[param])) { | |
throw new Error(`${ param } must be of type ${ paramDefs[param] }`); | |
} | |
}); | |
fn(...args); | |
}; | |
} | |
const asl = typedFunction({ age: Number, sex: String, loc: String }, (age, sex, loc) => { | |
// Never tell your true age | |
console.log(`${ age - 5 }, ${ sex }, ${ loc }`); | |
}); | |
const test = typedFunction({ x: null, y: undefined, z: NaN }, (x, y, z) => { | |
console.log('passed'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment