Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a function takes an array or single valued input

Tags:

javascript

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

  1. takes a single number argument and returns a new number or

  2. 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?

like image 848
Steve Ladavich Avatar asked Jul 28 '26 09:07

Steve Ladavich


1 Answers

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 type property to tell the mainFunction what's the expected type of the predicate function.

like image 148
Matías Fidemraizer Avatar answered Jul 29 '26 23:07

Matías Fidemraizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!