petrovicstefanrs / 30_seconds_of_knowledge

Google Chrome Extension that lets you gain new developer skills, every time you open a New Tab.
https://30secondsofknowledge.com/
MIT License
942 stars 121 forks source link

PHP - variadicFunction #49

Closed senky closed 5 years ago

senky commented 5 years ago

Hi, variadicFunction in PHP has quite wrong description and example. Variadic function is a function of any number of arguments. Not one argument of any length. So the code should look like:

function variadicFunction(...$operands)
{
    $sum = 0;
    foreach($operands as $singleOperand) {
        $sum += $singleOperand;
    }
    return $sum;
}

and an example:

variadicFunction(1, 2); // 3
variadicFunction(1, 2, 3, 4); // 10
petrovicstefanrs commented 5 years ago

@senky Quite right you are! 😄 Will fix this! What do you think, I believe the code could be even shorter with return array_sum($operands). If I'm correct, and please do tell me if I'm wrong, the ... in php take all the arguments and put them in an array so this array_sum should technically work. Still it would only work if parameters are numbers, otherwise a transformation function should be provided as a first parameter.

Hmmm now I'm a bit stumped, should I leave the example to work with numbers or should I expand it with a transformation function as well?

senky commented 5 years ago

@petrovicstefanrs I wouldn't mix variadic functions with higher order functions. Also I wouldn't use array_sum as it breaks all the wonder. 😅 But maybe you could add more semantics:

function variadicSum(...$operands)
...
petrovicstefanrs commented 5 years ago

@senky Welp I always forget that for a function to be a higher order function it only needs to accept a function as an argument not necessarily return a function as a result. (In my brain if it doesn't return a function its not a higher order function 😄) Anyway, keep it simple and change the name to actually mirror what the function does, okay like it! 😄