Create Set class - Node.js Data Structure

Node.js examples for Data Structure:Set

Description

Create Set class

Demo Code

function arrayToString(a) {
  return "[" + a.join(", ") + "]";
}

String.prototype.hashCode = function(s) {
  var hash = 0;//from   w w  w.  j a  v a  2  s  .  c  o  m
  if (this.length === 0) {
    return hash;
  }
  for (var i = 0; i < this.length; i++) {
    var character = this.charCodeAt(i);
    hash = ((hash << 5) - hash) + character;
    hash = hash & hash; // Convert to 32bit integer
  }
  return hash;
};

function standardEqualsFunction(a,b) {
  return a.equals(b);
}

function standardHashFunction(a) {
  return a.hashString();
}

function Set(hashFunction, equalsFunction) {
  this.data = {};
  this.hashFunction = hashFunction || standardHashFunction;
  this.equalsFunction = equalsFunction || standardEqualsFunction;
  return this;
}

Object.defineProperty(Set.prototype, "length", {
  get : function() {
    return this.values().length;
  }
});

Set.prototype.add = function(value) {
  var hash = this.hashFunction(value);
  var key = "hash_" + hash.hashCode();
  if(key in this.data) {
    var i;
    var values = this.data[key];
    for(i=0;i<values.length; i++) {
      if(this.equalsFunction(value, values[i])) {
        return values[i];
      }
    }
    values.push(value);
    return value;
  } else {
    this.data[key] = [ value ];
    return value;
  }
};

Set.prototype.contains = function(value) {
  var hash = this.hashFunction(value);
  var key = hash.hashCode();
  if(key in this.data) {
    var i;
    var values = this.data[key];
    for(i=0;i<values.length; i++) {
      if(this.equalsFunction(value, values[i])) {
        return true;
      }
    }
  }
  return false;
};

Set.prototype.values = function() {
  var l = [];
  for(var key in this.data) {
    if(key.indexOf("hash_")===0) {
      l = l.concat(this.data[key]);
    }
  }
  return l;
};

Set.prototype.toString = function() {
  return arrayToString(this.values());
};

Related Tutorials