4

I'm using an array in my object prototype which basically has add, remove, search functions attached to it.

Something like this

myobj = function() {
  this.Array_ = [];
}

myobj.prototype.add = function(item) {
  goog.array.insert(this.Array_, item);
}

myobj.prototype.hasItem = function(item) {
  goog.array.contains(this.Array_, item);
}

And a sample Array in my case would list of integers. [1, 2, 3, 4]

But later I learnt that this is very costly and can be cost saving if I use hash. Can someone explain use of hash with the above example.

3
  • 1
    possible duplicate of hashtable in javascript Commented Jun 17, 2012 at 8:49
  • That sounds like you're using it like you might a set. Commented Jun 17, 2012 at 9:44
  • @Sarfraz Solves my question thanks Commented Jun 17, 2012 at 11:49

1 Answer 1

8

The word "hash" has many meanings, but in this case it probably refers to generic javascript Objects, which are "hashtables" internally. Objects have "add" and "contains" functionality built-in:

foo = {}

foo['x'] = 1   // "add"
'x' in foo     // "contains"

Do note, however, that keys are always converted to strings, therefore if you want keys of other types (e.g. generic objects), you'll have to use custom functions, for example:

contains = function(ary, obj) {
    return ary.indexOf(obj) >= 0;
}

add = function(ary, obj) {
    if (!contains(ary, obj))
        ary.push(obj)
}
Sign up to request clarification or add additional context in comments.

1 Comment

By "there's no way to store an object in a hashtable" you mean "there's no way to store an object as a key in a hashtable"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.