0

I'm not sure if I'm very tired right now, but for some reason I can't get my head around this:

const A = new Set([1, 2, 3, 4, 5]);
const B = new Set([4, 5, 6, 7, 8]);
const C = new Set([9, 10]);

function exercise09(arg1, arg2) {
  var union = arg1;

  for (let elem of arg2) {
    union.add(elem);
  }

  console.log(union.size);
}

exercise09(A, A); // Should yield 5
exercise09(A, B); // Should yield 8
exercise09(A, C); // Should yield 7

If i run them independently I get the correct results, but when run consecutively they affect each other.

The 3rd call gives 10 instead of 7 when runned after the 2 first calls.

The value of "A" changes to contain 8 elements after the second call?

I don't understand why the function calls are affecting one and other?

Rajesh
  • 24,354
  • 5
  • 48
  • 79
ollebergkvist
  • 39
  • 1
  • 5
  • 2
    I think you are passing references to the sets as args. So when you call the union function on the first arg, you are changing the referenced set. You would need to create a new set object in the function – Zach Smith Nov 13 '20 at 03:57
  • of course! thank you very much – ollebergkvist Nov 13 '20 at 04:01

2 Answers2

2

make a copy of set and then work on it. var union = new Set(arg1)

deepak
  • 1,390
  • 1
  • 8
  • 12
1

You are mutating the set A which is arg1 because of the following line

union.add(elem);

You need to make a copy of arg1 and then assign to union

const A = new Set([1, 2, 3, 4, 5]);
const B = new Set([4, 5, 6, 7, 8]);
const C = new Set([9, 10]);

function exercise09(arg1, arg2) {
  var union = new Set([...arg1]);

  for (let elem of arg2) {
    union.add(elem);
  }

  console.log(union.size);
}

exercise09(A, A); // Should yield 5
exercise09(A, B); // Should yield 8
exercise09(A, C); // Should yield 7
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73