r/javascript • • Aug 27 '16

Is your JavaScript function actually pure?

http://staltz.com/is-your-javascript-function-actually-pure.html
8 Upvotes

48 comments sorted by

View all comments

3

u/NewazaBill Aug 27 '16 edited Aug 27 '16

While I like a lot of the work that André Staltz has done with Cycle and whatnot, god has he been just a pedantic asshole lately. So I'm going to be even more pedantic.

His example can be boiled down to this:

let x = [Math.random(), Math.random(), Math.random(), Math.random()];
sum(x);
x = [Math.random(), Math.random(), Math.random(), Math.random()];
sum(x);
x = [Math.random(), Math.random(), Math.random(), Math.random()];
sum(x);

Just because I changed what value x represents before each invocation, doesn't make sum impure. However, my program surely isn't pure, because each time I run it, it will output different results since Math.random() is calculated at runtime.

Now to get REALLY pedantic: the fact that we're passing an Array, which is a reference, DOES make the function impure. Consider this scenario:

const x = [1, 2, 3, 4];
doSomethingAsync().then(() => sum(x));
doAnotherAsyncThing().then(() => x.push(5));

This is a much more nefarious problem, because x can now change while sum is being executed. So I can actually have a scenario where this happens:

1. Call sum: sum(x), where x = [1, 2, 3 ,4]
2. Sum begins adding: +1, +2, +3...
3. Suddenly, x is mutated: x.push(5)
4. Returned value: 15.

The proper way to make the sum function pure would be:

function sum(...nums) {
     if (!nums) return void 0;
     var y = 0;
     for (var i = 0; i < nums.length; i++) {
         if (typeof nums[i] !== 'number') {
             return void 0;
         }
         y += nums[i];
     }
     return y;
}

sum(1, 2); // 3
let x = [1, 2, 3, 4];
// destructured at call site, therefore x's mutations
// can not impact sum's output.
sum(...x);

Anyway, I believe it's perfectly fine to use "pure" colloquially to mean that f(x) = y, as long as x is the same value. I just figured if we are going to be painfully pedantic, we may as well also be correct.

0

u/vinnl Aug 28 '16

It is sort-of pedantic, but the point is not that you should care about the extreme cases of non-purity. All it's trying to say is that there's more to purity then we often assume; that purity is a scale, and that e.g. types can help us edge a little bit more to the pure side of that scale.

Or at least, that was my takeaway. His conclusion seems to be more about using more pedantic language, which I agree is not that relevant.