JS Hash: Simple and easy!

Hello 🙂

Ima to publish my hash, yo! It is super-small easy to use, but do the job done lika pro, check it out!

Initialize

h = {}
//or...
h = { 'a' : 1, 2 : 'b', 'c' : 3}

Add a pair

h['z'] = 4
//or..
h.z = 4

Remove a pair

h[2] = null
//or
h[2] = undefined

Get the size

h.size()

Iterate All

// It outputs in the insertion order in my tests! BONUS :D
h.each( function(k,v){ console.log(k,v) } )

The souce-code:


Object.prototype.size = function() {
    var size = 0, key;
    for (key in this) {
        if (this.hasOwnProperty(key) && this[key] != null && this[key] != undefined ) size++;
    }
    return size;
};

Object.prototype.each = function(f )
{
  if (typeof f != "function") throw new TypeError();

  for (key in this) {
    if (this.hasOwnProperty(key) && this[key] != null && this[key] != undefined ) f.call(this, key, this[key]);
  }
};

Conclusion

In my opinion this is the easiest way to use a Hash in JS, for it is very natural to use the Object like a hash in JavaScript (– and not rightful :P)
It may occur some problems in the way that some people say it is not ok to prototype from Object (makes sense), i.e: this is not compatible with jQuery! For it does break with any Object extension (there is a issue currently about this)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s