Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Created September 29, 2011 18:01
Show Gist options
  • Save nwjsmith/1251435 to your computer and use it in GitHub Desktop.
Save nwjsmith/1251435 to your computer and use it in GitHub Desktop.
function HashMap () {
this._items = {};
this.length = 0;
}
HashMap.prototype.get = function (key) {
if (key === null || typeof this._items[this._hash(key)] === undefined) {
return null;
}
return this._items[this._hash(key)];
};
HashMap.prototype.put = function (key, value) {
this._items[this._hash(key)] = value;
this.length++;
};
HashMap.prototype._hash = function (value) {
if (value instanceof Object) {
return (typeof value) + " " + (value._hash || (value._hash = ++this._counter));
} else {
return (typeof value) + " " + value.toString();
}
};
HashMap.prototype._counter = 0;
function pairWithSum(sum, randoms) {
var deltas = new HashMap(), delta, i, l;
for (i = 0, l = randoms.length; i < l; i++) {
if (deltas.get(randoms[i])) {
return [ randoms[i], deltas.get(randoms[i]) ];
}
deltas.put(sum - randoms[i], randoms[i]);
}
}
pairWithSum(98, [100, 20, -2, 30, 4]); // => [-2, 100]
@thuva
Copy link

thuva commented Sep 29, 2011

function HashMap () {
  this._items = {};
  this.length = 0;
}

HashMap.prototype = {
  constructor: HashMap,
  _counter: 0,

  get: function (key) {
    if (key === null || typeof this._items[this._hash(key)] === undefined) {
      return null;
    }
    return this._items[this._hash(key)];
  },

  put: function (key, value) {
    this._items[this._hash(key)] = value;
    this.length++;
  },

  _hash: function (value) {
    if (value instanceof Object) {
      return (typeof value) + " " + (value._hash || (value._hash = ++this._counter));
    } else {
      return (typeof value) + " " + value.toString();
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment