Is it possible to determine whether or not a javascript function is "pure", using javascript?
A function is said to be pure when it behaves in a predictable way, in the sense that for each x, the function will always return the same associated y value (i.e a single-valued map).
For example, a pure function:
function pure(x) {
return x * x;
}
And impure:
var x = 0;
function impure(y) {
x = x + y;
return x++;
}
While it's easy to tell here that impure(0) !== impure(0)
, it isn't as apparent with a function such as:
function weird(x) {
if (x === "specificThing") {
return false;
} else {
return true;
}
}
or
var count = 0;
function surprise(x) {
count++;
if (count === 10e10 && x === 0) {
return true;
} else {
return false;
}
}
Another way of asking this is, is it possible to determine whether or not a javascript function is "impure", using javascript?
Theoretically it may be possible or impossible, but practically what steps can one take to start to determine this, maybe given a set of constraints or assumptions?
Another definition of purity includes the caveat that non-local variables may not be changed, but I'd like to consider that a separate problem. In this case we are considering functions that map consistent inputs to consistent outputs.
Math.random()
), then work your way up. It would certainly be interesting to see if someone has written a tool to do this. – Corroboreecount
in yoursurprise
function. – Hydrastininecount
was in an essentially no-op line of code. Or for example if count++; was still there, but it was removed from the if statement. – Tantan()
that sometime during it's execution calledm()
, andn()
is redefined to a different function.n()
purity is mutable in this case, and there's plenty of use-cases for functions calling other functions. – Olettaif
statement, where one branch is pure, the other is impure, and theif
condition is whether we're in the first second of a century. Would you consider it pure or impure? – Hydrastinine