4 ms·
The conventional definition of "pure" is that the result of the function is the same for the same input. You might include "throws an exception" as a possible
by klodolph 10y ago
The conventional definition of "pure" is that the result of the function is the same for the same input. You might include "throws an exception" as a possible "result" for a JavaScript function, or you might not (generally not).
So the fact that your implementation of mean() returns a float when you expected an int (honestly, there are no ints in JavaScript, just floats which happen to have integer values, why would you expect that?) or returns undefined doesn't mean that the function is impure, it just means that the function doesn't do what you thought that it should do.
For example, I can write the function:
function addOne(x) { return x + 1; }
I think there is no conceivable generally useful definition of "pure" under which this function is not pure, and yet... it could overflow the stack, it could run out of heap memory if you pass a string depending on how much heap memory is available...
The generally useful definition of "pure" is just that if f is pure, I can save y = f(x) and use y instead of f(x), or vice versa, or I can eliminate f(x) completely if I don't need the result. The fact that extreme corner cases, like out-of-memory situations, can result in slightly different behavior is something that we like to gloss over.