Skip to content

Instantly share code, notes, and snippets.

@fragoulis
Last active August 29, 2015 14:04
Show Gist options
  • Save fragoulis/35a2c3ec392472f7cb11 to your computer and use it in GitHub Desktop.
Save fragoulis/35a2c3ec392472f7cb11 to your computer and use it in GitHub Desktop.
Useful functions that could be considered as extentions to Javascript
/**
* Given an Object it returns its length.
* Much like returning the size of an
* associative array.
*
* Usage:
* ```js
* var size = Object.size(myObject);
* ```
*
* @param obj Object any javascript object
*
* @return integer the size of the object
*/
Object.size = function(obj)
{
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
// Better alternative?
// return Object.keys(obj).length;
};
/**
* Extends the Object prototype with the
* useful length() method which returns the
* number of the object's attributes.
*
* @return integer the number of attributes
*/
Object.prototype.length = function ()
{
return Object.size(this);
// return Object.keys(this).length;
}
var AssocArray = function ()
{
this.length = 0;
this.data = {};
}
AssocArray.prototype.set = function (key, value)
{
this.data[key] = value;
}
AssocArray.prototype.get = function (key)
{
return this.data[key];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment