Set that can `union` and `intersect` with another Set - Node.js Array

Node.js examples for Array:Set Operation

Description

Set that can `union` and `intersect` with another Set

Demo Code


/**//w ww  .ja  va 2  s . com
 * This is a general Set that can `union` and `intersect` with another Set
 * and uses the `equals` function of elements if they have one.
 * Other methods include `contains` and `equals`.
 */
function Set() {
  Array.call(this);
}
Set.prototype = Object.create(Array.prototype);
extend(Set.prototype, {
  push: function (elem) {
    if (!this.contains(elem))
      Array.prototype.push.call(this, elem);
    return this;
  },
  removeAll: function (other) {
    // TODO: custom indexOf that uses elem.equals
    var self = this;
    other.forEach(function (elem) {
      var index = self.indexOf(elem);
      if (index === -1)
        return;
      self.splice(index, 1);
    });
    return this;
  },
  copy: function () {
    var that = new Set();
    this.forEach(function (elem) {
      that.push(elem.copy && elem.copy() || copy(elem));
    });
    return that;
  },
  union: function (other) {
    other.forEach(this.push.bind(this));
    return this;
  },
  intersect: function (other) {
    for (var i = 0; i < this.length; i++) {
      if (!other.contains(this[i])) {
        this.splice(i, 1);
        i--;
      }
    }
    return this;
  },
  contains: function (elem) {
    return this.some(function (elemB) {
      return elem === elemB || elem && elem.equals && elem.equals(elemB) || equals(elem, elemB);
    });
  },
  equals: function (other) {
    if (other.length != this.length)
      return false;
    return this.every(function (elem) {
      return other.contains(elem);
    });
  }
});

function extend(a, b) {
  if (a && b) {
    for (var key in b) {
      a[key] = b[key];
    }
  }
  return a;
}

Related Tutorials