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.

3

u/hahaNodeJS Aug 28 '16

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

This is not the same as his example. Here, you have a set of random values that you keep changing. In Staltz's example, he has a set pointing to the random function.

1

u/vinnl Aug 28 '16

Exactly. Pure functions can return different outputs if the inputs are different, which is the case here.

1

u/hahaNodeJS Aug 29 '16

Right, but you're not addressing the same point the author is making. If you pass in the function Math.random, the method should always return the same value. In the case for a function f(x,y) that sums x, y, the returned value should be 0 if either x or y are non-numbers.

In your example you're simply passing in different numeric values for x,y,....

1

u/vinnl Aug 29 '16

Yes, that was what I was saying - the example wasn't mine :)