I am attempting to write a function that takes an array and another function as an input. The only thing I know about the supplied function though is that it either
takes a single number argument and returns a new number or
takes an array of numbers and returns a new array of numbers.
In my function, I want to check whether it's the first or second case to determine whether or not to call the supplied function with Array.prototype.map().
So with these two functions...
var unknownFunction = function( unknownInput ) {
//Does stuff with input
//returns number or array of numbers...
return someValueOrValues
}
and
var mainFunction = function( anArray, preFunction ){
// SOME CODE TO CHECK IF ARG NEEDS TO BE NUMBER OR ARRAY
// ...
// ...
**ANSWER WOULD FIT HERE**
if( argIsNumber === true ){
// function takes NUMBER
anArray = anArray.map( preFunction )
}else{
// function takes ARRAY
anArray = preFunction(anArray)
}
// DO STUFF WITH ARRAY AFTER USER FUNCTION HAS MADE IT'S MODIFICATIONS
// ...
// ...
// ...
return anArray;
}
is there any way to poke inside the first function to figure out how best to call it?
Since JavaScript is a dynamically-typed language, function's input parameters have type once some calls it with some argument.
One elegant and possible approach is adding a property to the whole given function to hint the input parameter type:
var func = function() {};
func.type = "number"; // a function decorator
var mainFunction = function(anArray, inputFunc) {
if(typeof inputFunc != "function") {
throw Error("Please supply a function as 'inputFunc'!");
}
switch(inputFunc.type) {
case "number":
return anArray.map(preFunction);
case "array":
return preFunction(anArray);
default:
throw Error("Type not supported");
}
};
mainFunction([1,2,3], func);
When you work with dynamically-typed languages you need to think about coding using convention over configuration and/or using duck typing. Type safety provided by strongly-typed languages is replaced by a good documentation.
For example:
Provide a function as second parameter with a
typeproperty to tell themainFunctionwhat's the expected type of the predicate function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With