Search code examples
javascriptpurely-functional

Why this snippet is not pure?


When I watch Google Chrome Developers, https://youtu.be/qaGjS7-qWzg?t=636

They said this snippet is not pure. I don't know why.

const g = new Map();

for (const [u,v] of edges) {
    if (!g.has(u))
        g.set(u, []);
    if (!g.has(v))
        g.set(v, []);
    g.get(u).push(v)
}

And they also mentioned this is pure,

const startPoints = new Set(edges.map(([u, v]) => u));

const g = new Map(
  [...startPoints].map(startPoint =>
    edges.filter(([u, v]) => u == startPoint).map(([u, v]) => v)
  )
);


Solution

  • When we talk about purity in a system we are talking about a system that doesn't change the observable state.

    • In the first script at line 1 g is an empty Map and by the last line it is not. Its value was mutated.
    • In the second script startPoints is the same thing at line one and at the end.

    To make it a little easy, let me explain it with a function. Let's suppose you have a function that giving an array of numbers it multiply it by 2. So if:

    var a = [1,2,3];
    multiply(a)
    // a = [2, 4, 6]
    

    This function is not pure. It has changed the observable state of the system that in this case is a. But if:

    var a = [1,2,3];
    var b = multiply(a)
    // a = [1, 2, 3]
    // b = [2, 4, 6]
    

    This function is pure. a didn't change.