Last Updated: February 25, 2016
·
231
· doublejosh

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;
    }
  };
};