title: Ergonomic way of only adding a new object to a map if it doesn't exist?
body: <p>I am developing a game where it is very often that I wish to perform the following operation:</p>
  <pre><code>if (!buffs.has(&quot;shielding&quot;)) {
    buffs.add(new ShieldingBuff(50)); // 50 is the shield amount
  }
  </code></pre>
  <p>where <code>buffs</code> type is <code>Map&lt;string, Buff&gt;</code>.</p>
  <p>I thought to wrap it in a helper function like so:</p>
  <pre><code>function addBuff(buffType, buff) {
    if (!this.buffs.has(buffType) {
      this.buffs.add(buff);
    }
  }
  </code></pre>
  <p>and then calling it like this:</p>
  <pre><code>addBuff(&quot;shielding&quot;, new ShieldingBuff(50));
  </code></pre>
  <p>But the problem with that is that in 99% of cases the buff will already be applied, and this incurs a significant garbage collection cost, since we're allocating a <code>ShieldingBuff</code> object regardless of whether or not we actually need it.</p>
  <p>I was thinking about maybe using short-circuiting somehow, but I cannot think of an ergonomic way of doing it. The best I could do is come up with something like this:</p>
  <pre><code>buffs.add(!buffs.has(&quot;shielding&quot;) &amp;&amp; new ShieldingBuff(50));
  </code></pre>
  <p>which works to avoid the allocation in the case the buff is already applied.. but is still rather verbose. Ideally I would be able to encapsulate the <code>has</code> check into the helper function somehow, but I can't see a way to do that while maintaining the short-circuiting trick to avoid the allocation in the majority case where the buff is already applied and nothing need be done.</p>
  <p>My worry is that if I have to remember to call the <code>has</code> check every time, eventually I'll forget and it will lead to a bug. I would like to avoid that if possible.</p>