Ultra-light-weight basic object convenience methods class
Here's a handy, tiny class for dealing with JS objects like arrays. Useful if you want to skip an Underscore or Lo-Dash dependency.
https://gist.github.com/doublejosh/16bc0017bb8d1091971c
Collection = function (obj) {
// Private vars.
var keyList = null,
length = null;
// Public functions.
return {
/**
* Get the property keys of an object.
*
* param {object} obj
* Oject to be inspected.
* return {array}
* List of object properties.
*/
keys : function() {
if (keyList === null) {
keyList = [];
for (var key in obj) keyList.push(key);
}
return keyList.sort();
},
/**
* Get the size of an object.
*
* param {object} obj
* Oject to be inspected.
* return {number}
* Size of the object.
*/
size : function () {
if (obj == null) return 0;
if (length === null) {
length = this.keys().length;
}
return length;
},
/**
* Access the object from this instance.
*
* return {object}
* Use what you started with.
*/
get : function () {
return obj;
}
};
};Written by Josh Lind
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#