This is an answer to a SO question:
function typedFunction(paramsList, f){
//optionally, ensure that typedFunction is being called properly -- here's a start:
if (!(paramsList instanceof Array)) throw Error('invalid argument: paramsList must be an array');
//the type-checked function
return function(){
for(var i=0,p,arg;p=paramsList[i],arg=arguments[i],i<paramsList.length; i++){
if (typeof p === 'string'){
if (typeof arg !== p) throw new Error('expected type ' + p + ', got ' + typeof arg);
}
else { //function
if (!(arg instanceof p)) throw new Error('expected type ' + String(p).replace(/\s*\{.*/, '') + ', got ' + typeof arg);
}
}
//type checking passed; call the function itself
return f.apply(this, arguments);
};
}
//usage:
var ds = typedFunction([Date, 'string'], function(d, s){
console.log(d.toDateString(), s.substr(0));
});
ds('notadate', 'test');
//Error: expected type function Date(), got string
ds();
//Error: expected type function Date(), got undefined
ds(new Date(), 42);
//Error: expected type string, got number
ds(new Date(), 'success');
//Fri Jun 14 2013 success
It shows a generalized way of ensuring arguments conform to specified types. I am having a hard time grasping the flow of arguments from the ds
function call, back to the function that is returned from typedFunction()
.
Here's what I expect:
paramsList
should refer to the first parameter intypedFunction()
's functionarguments
should refer to a list of all arguments passed totypedFunction
, in this case bothparamsList
andf
. However, it seems likearguments
refers to the arguments passed inds
. That's where things get fuzzy. How do the arguments supplied inds
get passed tof
?
Could you explain the logical flow of events/ how this code works?
Sorry if the question is not clear. Please edit the question if you have a grasp of what I'm trying to ask and can make the question easier to read.