1 /** 2 * @fileOverview This file contains new methods for the Object class 3 */ 4 /** 5 * @name Object 6 * @class The built-in object class which all objects prototype which acts somewhat like a hash of key/value pairs. 7 */ 8 9 /** 10 * Returns a new object with the passed object's keys as the new object's values 11 * and the passed object's values as the keys to those values. 12 * 13 * @param {Object} obj The object to create an inverted object from 14 * @return {Object} The inverted object 15 */ 16 Object.invert = function invert(obj) { 17 var o = {}; 18 for( var k in obj ) 19 if( obj.hasOwnProperty(k) ) 20 o[obj[k]] = k; 21 return o; 22 }; 23 24 /** 25 * Merges multiple objects together into the first object with a right dominant pattern. 26 * This will modify the first object and override methods with the rightmost value. 27 * 28 * This method returns the object that was modified, so if you would like a new 29 * object instead of one of your objects being overwritten use `Object.merge({}, ...);` 30 * 31 * @param {Boolean} [deep=false] Use a deep object merge 32 * @param {Object} ... Objects to merge 33 * @return {Object} The first object passed to merge 34 */ 35 Object.merge = function merge() { 36 var a = Array.slice(arguments), left, deep = false; 37 if ( typeof a[0] === 'boolean' ) 38 deep = a.shift(); 39 left = a.shift(); 40 if ( left === null || typeof left !== 'object' ) 41 throw new TypeError(); 42 for ( var i = 0, l = a.length; i<l; i++ ) { 43 var right = a[i]; 44 for ( var key in right ) 45 if ( right.hasOwnProperty(key) ) 46 if ( deep && isObject(left[key]) && isObject(right[key]) ) 47 left[key] = merge( left[key], right[key] ); 48 else 49 left[key] = right[key]; 50 } 51 return left; 52 }; 53 54 /** 55 * Return the number of key/value pairs within an object 56 * 57 * @param {Object} obj The object to count 58 * @return {Number} The number of pairs in the object 59 */ 60 (function(useCount) { 61 Object.count = function count(obj) { 62 if ( useCount ) return obj.__count__; 63 return Object.keys(obj).length; 64 }; 65 })(({}).__count__ === 0); 66 67 /** 68 * Return an array containing the list of keys within the object 69 * 70 * @param {Object} obj The object to take keys from 71 * @return {Array} The array of keys 72 */ 73 Object.keys = function keys(obj) { 74 var keys = []; 75 for ( var k in obj ) 76 if ( obj.hasOwnProperty( k ) ) 77 keys.push( k ); 78 return keys; 79 }; 80 81 /** 82 * Return an array containing the list of values within the object 83 * 84 * @param {Object} obj The object to take values from 85 * @return {Array} The array of values 86 */ 87 Object.values = function values(obj) { 88 var values = []; 89 for ( var k in obj ) 90 if ( obj.hasOwnProperty( k ) ) 91 values.push( obj[k] ); 92 return values; 93 }; 94 95