Created
December 11, 2011 13:48
-
-
Save rosylilly/1460700 to your computer and use it in GitHub Desktop.
適当にJavascriptで型チェック
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 TypeCheck(func) { | |
var argumentTypes = []; | |
var functionString = func.toString().replace(/\n/g, ' '); | |
var argumentString = functionString.replace(/^function.*?\(/, '').replace(/\).*$/,''); | |
var argumentTypes = argumentString.split(','); | |
for(var i=0,l=argumentTypes.length; i<l; i++) { | |
var match = argumentTypes[i].match(/\/\*\*(.*)\*\//); | |
if(match) { | |
argumentTypes[i] = match[1].replace(/^ *| *$/g,'').toLowerCase(); | |
} else { | |
argumentTypes[i] = null; | |
} | |
}; | |
var newFunction = function() { | |
var argsSize = arguments.length; | |
if (argsSize != argumentTypes.length) { | |
throw new Error("引数の数が不正です: " + argsSize + "/" + argumentTypes.length); | |
} | |
for(var i=0; i < argsSize; i++) { | |
var type = argumentTypes[i]; | |
if(!type) continue; | |
var arg = arguments[i]; | |
if (typeof arg != type) { | |
throw new Error("引数の型が不正です: "+ (typeof arg) + "/" + type); | |
} | |
} | |
newFunction.originalFunction.apply(null, arguments); | |
}; | |
newFunction.originalFunction = func; | |
return newFunction; | |
}; | |
var localVar = 1; | |
var testFunction = function(int/** Number */, string/** String */, any) { | |
console.log(localVar, int, string, any); | |
}; | |
localVar = "Called: "; | |
testFunction(1, 'string'); | |
typeCheckingTestFunction = new TypeCheck(testFunction); | |
try{ | |
typeCheckingTestFunction(1, 'string'); | |
}catch(e) { | |
console.log(e.message); | |
}; | |
try{ | |
typeCheckingTestFunction(1, 2, null); | |
}catch(e) { | |
console.log(e.message); | |
}; | |
typeCheckingTestFunction(1, "str", 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment