0

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)
  )
);

foxiris
  • 3,125
  • 32
  • 32

1 Answers1

4

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.

Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96
Johnny Zabala
  • 2,285
  • 1
  • 12
  • 14
  • So you can't use something like `pop`, `push` in the pure world? Seems You have to assign a new variable when you want to mutate an Object/Array every time. – foxiris Feb 09 '20 at 12:53
  • Exactly in a pure world (that JavaScript is not), you create new copies every time you want to mutate the state. In JS there is a lib that does that https://immutable-js.github.io/immutable-js/. – Johnny Zabala Feb 09 '20 at 12:58