congusbongus
congusbongus

Reputation: 14657

How to add to a set without mutating it?

I want to add an item to a Set without mutating the original set. I tried using add() but this mutates the original:

var s = new Set();
var s1 = s.add('foo');
console.log('s has foo:', s.has('foo'));
console.log('s1 has foo:', s1.has('foo'));

How can I create a new set by adding an item to it, without mutating the original set?

Upvotes: 1

Views: 419

Answers (1)

congusbongus
congusbongus

Reputation: 14657

You can create a new set from the original, then add the item to the new set:

var s = new Set();
var s1 = new Set(s);
s1.add('foo');
console.log('s has foo:', s.has('foo'));
console.log('s1 has foo:', s1.has('foo'));

Upvotes: 2

Related Questions