3 ms·
maybe I'm wrong but the last example of pureFunction mutates and returns one of its arguments. That's not a pure function.
by sjclemmy 10y ago
maybe I'm wrong but the last example of pureFunction mutates and returns one of its arguments. That's not a pure function.
- Lerc 10y agoThat's what struck me too. It's the strangest thing. Is it Cargo Cult functional programming?
- stillworks 10y agoYes... that's odd ! I would have thought something like "if last element then generate a new list else to prefix append result of recursion"
- wereHamster 10y agoIt can be considered pure when you only give it one or two arguments (the second argument can be allowed because numbers are passed by value and not reference in JavaScript). Default arguments make the code harder to understand. It's often better to make two functions. If they are closely related then you can implement one in terms of the other. Even worse if the function behaves completely differently depending on how many arguments it takes (take the D3 setters/getters as an example). function pureFunction(data) { return pureFunctionWithIndexAndResult(data, 0, []); } function pureFunctionWithIndexAndResult(data, index, result) { ... }
- sjclemmy 10y agoIt doesn't matter how many arguments there are. My point was that calling the function will mutate one of its arguments and in fact, in the example the returned value of the function is irrelevant because nothing is assigned to the return value of the function when it is invoked. So it's actually just plain wrong. The function is called and a side effect of calling the function is the mutation of the supplied 'result' argument. Call the function 4 times and you get a different result every time. Not a pure function.
- bepitulaz 10y agoYou were right. I updated the sample in article. It is using `concat`. > The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments. Taken from the MDN.