title: How to map/reduce/filter a Set in JavaScript?
body: <p>Is there any way to <code>map</code>/<code>reduce</code>/<code>filter</code>/etc a <code>Set</code> in JavaScript or will I have to write my own?</p>
  
  <p>Here's some sensible <code>Set.prototype</code> extensions</p>
  
  <pre><code>Set.prototype.map = function map(f) {
    var newSet = new Set();
    for (var v of this.values()) newSet.add(f(v));
    return newSet;
  };
  
  Set.prototype.reduce = function(f,initial) {
    var result = initial;
    for (var v of this) result = f(result, v);
    return result;
  };
  
  Set.prototype.filter = function filter(f) {
    var newSet = new Set();
    for (var v of this) if(f(v)) newSet.add(v);
    return newSet;
  };
  
  Set.prototype.every = function every(f) {
    for (var v of this) if (!f(v)) return false;
    return true;
  };
  
  Set.prototype.some = function some(f) {
    for (var v of this) if (f(v)) return true;
    return false;
  };
  </code></pre>
  
  <p>Let's take a little set</p>
  
  <pre><code>let s = new Set([1,2,3,4]);
  </code></pre>
  
  <p>And some stupid little functions</p>
  
  <pre><code>const times10 = x =&gt; x * 10;
  const add = (x,y) =&gt; x + y;
  const even = x =&gt; x % 2 === 0;
  </code></pre>
  
  <p>And see how they work</p>
  
  <pre><code>s.map(times10);    //=&gt; Set {10,20,30,40}
  s.reduce(add, 0);  //=&gt; 10
  s.filter(even);    //=&gt; Set {2,4}
  s.every(even);     //=&gt; false
  s.some(even);      //=&gt; true
  </code></pre>
  
  <blockquote>
    <p>Isn't that nice ? Yeah, I think so too. Compare that to the ugly iterator usage</p>
  </blockquote>
  
  <pre><code>// puke
  let newSet = new Set();
  for (let v in s) {
    newSet.add(times10(v));
  }
  </code></pre>
  
  <p>And</p>
  
  <pre><code>// barf
  let sum = 0;
  for (let v in s) {
    sum = sum + v;
  }
  </code></pre>
  
  <p>Is there any better way to accomplish <code>map</code> and <code>reduce</code> using a <code>Set</code> in JavaScript?</p>