Debian Codegraph @

closure-library/closure/goog/object/object.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Utilities for manipulating objects/maps/hashes.
17 * @author [email protected] (Erik Arvidsson)
18 */
19
20 goog.provide('goog.object');
21
22
23 /**
24 * Whether two values are not observably distinguishable. This
25 * correctly detects that 0 is not the same as -0 and two NaNs are
26 * practically equivalent.
27 *
28 * The implementation is as suggested by harmony:egal proposal.
29 *
30 * @param {*} v The first value to compare.
31 * @param {*} v2 The second value to compare.
32 * @return {boolean} Whether two values are not observably distinguishable.
33 * @see http://wiki.ecmascript.org/doku.php?id=harmony:egal
34 */
35 goog.object.is = function(v, v2) {
36 if (v === v2) {
37 // 0 === -0, but they are not identical.
38 // We need the cast because the compiler requires that v2 is a
39 // number (although 1/v2 works with non-number). We cast to ? to
40 // stop the compiler from type-checking this statement.
41 return v !== 0 || 1 / v === 1 / /** @type {?} */ (v2);
42 }
43
44 // NaN is non-reflexive: NaN !== NaN, although they are identical.
45 return v !== v && v2 !== v2;
46 };
47
48
49 /**
50 * Calls a function for each element in an object/map/hash.
51 *
52 * @param {Object<K,V>} obj The object over which to iterate.
53 * @param {function(this:T,V,?,Object<K,V>):?} f The function to call
54 * for every element. This function takes 3 arguments (the value, the
55 * key and the object) and the return value is ignored.
56 * @param {T=} opt_obj This is used as the 'this' object within f.
57 * @template T,K,V
58 */
59 goog.object.forEach = function(obj, f, opt_obj) {
60 for (var key in obj) {
61 f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);
62 }
63 };
64
65
66 /**
67 * Calls a function for each element in an object/map/hash. If that call returns
68 * true, adds the element to a new object.
69 *
70 * @param {Object<K,V>} obj The object over which to iterate.
71 * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to call
72 * for every element. This
73 * function takes 3 arguments (the value, the key and the object)
74 * and should return a boolean. If the return value is true the
75 * element is added to the result object. If it is false the
76 * element is not included.
77 * @param {T=} opt_obj This is used as the 'this' object within f.
78 * @return {!Object<K,V>} a new object in which only elements that passed the
79 * test are present.
80 * @template T,K,V
81 */
82 goog.object.filter = function(obj, f, opt_obj) {
83 var res = {};
84 for (var key in obj) {
85 if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {
86 res[key] = obj[key];
87 }
88 }
89 return res;
90 };
91
92
93 /**
94 * For every element in an object/map/hash calls a function and inserts the
95 * result into a new object.
96 *
97 * @param {Object<K,V>} obj The object over which to iterate.
98 * @param {function(this:T,V,?,Object<K,V>):R} f The function to call
99 * for every element. This function
100 * takes 3 arguments (the value, the key and the object)
101 * and should return something. The result will be inserted
102 * into a new object.
103 * @param {T=} opt_obj This is used as the 'this' object within f.
104 * @return {!Object<K,R>} a new object with the results from f.
105 * @template T,K,V,R
106 */
107 goog.object.map = function(obj, f, opt_obj) {
108 var res = {};
109 for (var key in obj) {
110 res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);
111 }
112 return res;
113 };
114
115
116 /**
117 * Calls a function for each element in an object/map/hash. If any
118 * call returns true, returns true (without checking the rest). If
119 * all calls return false, returns false.
120 *
121 * @param {Object<K,V>} obj The object to check.
122 * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to
123 * call for every element. This function
124 * takes 3 arguments (the value, the key and the object) and should
125 * return a boolean.
126 * @param {T=} opt_obj This is used as the 'this' object within f.
127 * @return {boolean} true if any element passes the test.
128 * @template T,K,V
129 */
130 goog.object.some = function(obj, f, opt_obj) {
131 for (var key in obj) {
132 if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {
133 return true;
134 }
135 }
136 return false;
137 };
138
139
140 /**
141 * Calls a function for each element in an object/map/hash. If
142 * all calls return true, returns true. If any call returns false, returns
143 * false at this point and does not continue to check the remaining elements.
144 *
145 * @param {Object<K,V>} obj The object to check.
146 * @param {?function(this:T,V,?,Object<K,V>):boolean} f The function to
147 * call for every element. This function
148 * takes 3 arguments (the value, the key and the object) and should
149 * return a boolean.
150 * @param {T=} opt_obj This is used as the 'this' object within f.
151 * @return {boolean} false if any element fails the test.
152 * @template T,K,V
153 */
154 goog.object.every = function(obj, f, opt_obj) {
155 for (var key in obj) {
156 if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {
157 return false;
158 }
159 }
160 return true;
161 };
162
163
164 /**
165 * Returns the number of key-value pairs in the object map.
166 *
167 * @param {Object} obj The object for which to get the number of key-value
168 * pairs.
169 * @return {number} The number of key-value pairs in the object map.
170 */
171 goog.object.getCount = function(obj) {
172 var rv = 0;
173 for (var key in obj) {
174 rv++;
175 }
176 return rv;
177 };
178
179
180 /**
181 * Returns one key from the object map, if any exists.
182 * For map literals the returned key will be the first one in most of the
183 * browsers (a know exception is Konqueror).
184 *
185 * @param {Object} obj The object to pick a key from.
186 * @return {string|undefined} The key or undefined if the object is empty.
187 */
188 goog.object.getAnyKey = function(obj) {
189 for (var key in obj) {
190 return key;
191 }
192 };
193
194
195 /**
196 * Returns one value from the object map, if any exists.
197 * For map literals the returned value will be the first one in most of the
198 * browsers (a know exception is Konqueror).
199 *
200 * @param {Object<K,V>} obj The object to pick a value from.
201 * @return {V|undefined} The value or undefined if the object is empty.
202 * @template K,V
203 */
204 goog.object.getAnyValue = function(obj) {
205 for (var key in obj) {
206 return obj[key];
207 }
208 };
209
210
211 /**
212 * Whether the object/hash/map contains the given object as a value.
213 * An alias for goog.object.containsValue(obj, val).
214 *
215 * @param {Object<K,V>} obj The object in which to look for val.
216 * @param {V} val The object for which to check.
217 * @return {boolean} true if val is present.
218 * @template K,V
219 */
220 goog.object.contains = function(obj, val) {
221 return goog.object.containsValue(obj, val);
222 };
223
224
225 /**
226 * Returns the values of the object/map/hash.
227 *
228 * @param {Object<K,V>} obj The object from which to get the values.
229 * @return {!Array<V>} The values in the object/map/hash.
230 * @template K,V
231 */
232 goog.object.getValues = function(obj) {
233 var res = [];
234 var i = 0;
235 for (var key in obj) {
236 res[i++] = obj[key];
237 }
238 return res;
239 };
240
241
242 /**
243 * Returns the keys of the object/map/hash.
244 *
245 * @param {Object} obj The object from which to get the keys.
246 * @return {!Array<string>} Array of property keys.
247 */
248 goog.object.getKeys = function(obj) {
249 var res = [];
250 var i = 0;
251 for (var key in obj) {
252 res[i++] = key;
253 }
254 return res;
255 };
256
257
258 /**
259 * Get a value from an object multiple levels deep. This is useful for
260 * pulling values from deeply nested objects, such as JSON responses.
261 * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)
262 *
263 * @param {!Object} obj An object to get the value from. Can be array-like.
264 * @param {...(string|number|!IArrayLike<number|string>)}
265 * var_args A number of keys
266 * (as strings, or numbers, for array-like objects). Can also be
267 * specified as a single array of keys.
268 * @return {*} The resulting value. If, at any point, the value for a key
269 * in the current object is null or undefined, returns undefined.
270 */
271 goog.object.getValueByKeys = function(obj, var_args) {
272 var isArrayLike = goog.isArrayLike(var_args);
273 var keys = isArrayLike ? var_args : arguments;
274
275 // Start with the 2nd parameter for the variable parameters syntax.
276 for (var i = isArrayLike ? 0 : 1; i < keys.length; i++) {
277 if (obj == null) return undefined;
278 obj = obj[keys[i]];
279 }
280
281 return obj;
282 };
283
284
285 /**
286 * Whether the object/map/hash contains the given key.
287 *
288 * @param {Object} obj The object in which to look for key.
289 * @param {?} key The key for which to check.
290 * @return {boolean} true If the map contains the key.
291 */
292 goog.object.containsKey = function(obj, key) {
293 return obj !== null && key in obj;
294 };
295
296
297 /**
298 * Whether the object/map/hash contains the given value. This is O(n).
299 *
300 * @param {Object<K,V>} obj The object in which to look for val.
301 * @param {V} val The value for which to check.
302 * @return {boolean} true If the map contains the value.
303 * @template K,V
304 */
305 goog.object.containsValue = function(obj, val) {
306 for (var key in obj) {
307 if (obj[key] == val) {
308 return true;
309 }
310 }
311 return false;
312 };
313
314
315 /**
316 * Searches an object for an element that satisfies the given condition and
317 * returns its key.
318 * @param {Object<K,V>} obj The object to search in.
319 * @param {function(this:T,V,string,Object<K,V>):boolean} f The
320 * function to call for every element. Takes 3 arguments (the value,
321 * the key and the object) and should return a boolean.
322 * @param {T=} opt_this An optional "this" context for the function.
323 * @return {string|undefined} The key of an element for which the function
324 * returns true or undefined if no such element is found.
325 * @template T,K,V
326 */
327 goog.object.findKey = function(obj, f, opt_this) {
328 for (var key in obj) {
329 if (f.call(/** @type {?} */ (opt_this), obj[key], key, obj)) {
330 return key;
331 }
332 }
333 return undefined;
334 };
335
336
337 /**
338 * Searches an object for an element that satisfies the given condition and
339 * returns its value.
340 * @param {Object<K,V>} obj The object to search in.
341 * @param {function(this:T,V,string,Object<K,V>):boolean} f The function
342 * to call for every element. Takes 3 arguments (the value, the key
343 * and the object) and should return a boolean.
344 * @param {T=} opt_this An optional "this" context for the function.
345 * @return {V} The value of an element for which the function returns true or
346 * undefined if no such element is found.
347 * @template T,K,V
348 */
349 goog.object.findValue = function(obj, f, opt_this) {
350 var key = goog.object.findKey(obj, f, opt_this);
351 return key && obj[key];
352 };
353
354
355 /**
356 * Whether the object/map/hash is empty.
357 *
358 * @param {Object} obj The object to test.
359 * @return {boolean} true if obj is empty.
360 */
361 goog.object.isEmpty = function(obj) {
362 for (var key in obj) {
363 return false;
364 }
365 return true;
366 };
367
368
369 /**
370 * Removes all key value pairs from the object/map/hash.
371 *
372 * @param {Object} obj The object to clear.
373 */
374 goog.object.clear = function(obj) {
375 for (var i in obj) {
376 delete obj[i];
377 }
378 };
379
380
381 /**
382 * Removes a key-value pair based on the key.
383 *
384 * @param {Object} obj The object from which to remove the key.
385 * @param {?} key The key to remove.
386 * @return {boolean} Whether an element was removed.
387 */
388 goog.object.remove = function(obj, key) {
389 var rv;
390 if (rv = key in /** @type {!Object} */ (obj)) {
391 delete obj[key];
392 }
393 return rv;
394 };
395
396
397 /**
398 * Adds a key-value pair to the object. Throws an exception if the key is
399 * already in use. Use set if you want to change an existing pair.
400 *
401 * @param {Object<K,V>} obj The object to which to add the key-value pair.
402 * @param {string} key The key to add.
403 * @param {V} val The value to add.
404 * @template K,V
405 */
406 goog.object.add = function(obj, key, val) {
407 if (obj !== null && key in obj) {
408 throw new Error('The object already contains the key "' + key + '"');
409 }
410 goog.object.set(obj, key, val);
411 };
412
413
414 /**
415 * Returns the value for the given key.
416 *
417 * @param {Object<K,V>} obj The object from which to get the value.
418 * @param {string} key The key for which to get the value.
419 * @param {R=} opt_val The value to return if no item is found for the given
420 * key (default is undefined).
421 * @return {V|R|undefined} The value for the given key.
422 * @template K,V,R
423 */
424 goog.object.get = function(obj, key, opt_val) {
425 if (obj !== null && key in obj) {
426 return obj[key];
427 }
428 return opt_val;
429 };
430
431
432 /**
433 * Adds a key-value pair to the object/map/hash.
434 *
435 * @param {Object<K,V>} obj The object to which to add the key-value pair.
436 * @param {string} key The key to add.
437 * @param {V} value The value to add.
438 * @template K,V
439 */
440 goog.object.set = function(obj, key, value) {
441 obj[key] = value;
442 };
443
444
445 /**
446 * Adds a key-value pair to the object/map/hash if it doesn't exist yet.
447 *
448 * @param {Object<K,V>} obj The object to which to add the key-value pair.
449 * @param {string} key The key to add.
450 * @param {V} value The value to add if the key wasn't present.
451 * @return {V} The value of the entry at the end of the function.
452 * @template K,V
453 */
454 goog.object.setIfUndefined = function(obj, key, value) {
455 return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);
456 };
457
458
459 /**
460 * Sets a key and value to an object if the key is not set. The value will be
461 * the return value of the given function. If the key already exists, the
462 * object will not be changed and the function will not be called (the function
463 * will be lazily evaluated -- only called if necessary).
464 *
465 * This function is particularly useful for use with a map used a as a cache.
466 *
467 * @param {!Object<K,V>} obj The object to which to add the key-value pair.
468 * @param {string} key The key to add.
469 * @param {function():V} f The value to add if the key wasn't present.
470 * @return {V} The value of the entry at the end of the function.
471 * @template K,V
472 */
473 goog.object.setWithReturnValueIfNotSet = function(obj, key, f) {
474 if (key in obj) {
475 return obj[key];
476 }
477
478 var val = f();
479 obj[key] = val;
480 return val;
481 };
482
483
484 /**
485 * Compares two objects for equality using === on the values.
486 *
487 * @param {!Object<K,V>} a
488 * @param {!Object<K,V>} b
489 * @return {boolean}
490 * @template K,V
491 */
492 goog.object.equals = function(a, b) {
493 for (var k in a) {
494 if (!(k in b) || a[k] !== b[k]) {
495 return false;
496 }
497 }
498 for (var k in b) {
499 if (!(k in a)) {
500 return false;
501 }
502 }
503 return true;
504 };
505
506
507 /**
508 * Returns a shallow clone of the object.
509 *
510 * @param {Object<K,V>} obj Object to clone.
511 * @return {!Object<K,V>} Clone of the input object.
512 * @template K,V
513 */
514 goog.object.clone = function(obj) {
515 // We cannot use the prototype trick because a lot of methods depend on where
516 // the actual key is set.
517
518 var res = {};
519 for (var key in obj) {
520 res[key] = obj[key];
521 }
522 return res;
523 // We could also use goog.mixin but I wanted this to be independent from that.
524 };
525
526
527 /**
528 * Clones a value. The input may be an Object, Array, or basic type. Objects and
529 * arrays will be cloned recursively.
530 *
531 * WARNINGS:
532 * <code>goog.object.unsafeClone</code> does not detect reference loops. Objects
533 * that refer to themselves will cause infinite recursion.
534 *
535 * <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and
536 * copies UIDs created by <code>getUid</code> into cloned results.
537 *
538 * @param {T} obj The value to clone.
539 * @return {T} A clone of the input value.
540 * @template T
541 */
542 goog.object.unsafeClone = function(obj) {
543 var type = goog.typeOf(obj);
544 if (type == 'object' || type == 'array') {
545 if (goog.isFunction(obj.clone)) {
546 return obj.clone();
547 }
548 var clone = type == 'array' ? [] : {};
549 for (var key in obj) {
550 clone[key] = goog.object.unsafeClone(obj[key]);
551 }
552 return clone;
553 }
554
555 return obj;
556 };
557
558
559 /**
560 * Returns a new object in which all the keys and values are interchanged
561 * (keys become values and values become keys). If multiple keys map to the
562 * same value, the chosen transposed value is implementation-dependent.
563 *
564 * @param {Object} obj The object to transpose.
565 * @return {!Object} The transposed object.
566 */
567 goog.object.transpose = function(obj) {
568 var transposed = {};
569 for (var key in obj) {
570 transposed[obj[key]] = key;
571 }
572 return transposed;
573 };
574
575
576 /**
577 * The names of the fields that are defined on Object.prototype.
578 * @type {Array<string>}
579 * @private
580 */
581 goog.object.PROTOTYPE_FIELDS_ = [
582 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
583 'toLocaleString', 'toString', 'valueOf'
584 ];
585
586
587 /**
588 * Extends an object with another object.
589 * This operates 'in-place'; it does not create a new Object.
590 *
591 * Example:
592 * var o = {};
593 * goog.object.extend(o, {a: 0, b: 1});
594 * o; // {a: 0, b: 1}
595 * goog.object.extend(o, {b: 2, c: 3});
596 * o; // {a: 0, b: 2, c: 3}
597 *
598 * @param {Object} target The object to modify. Existing properties will be
599 * overwritten if they are also present in one of the objects in
600 * {@code var_args}.
601 * @param {...Object} var_args The objects from which values will be copied.
602 */
603 goog.object.extend = function(target, var_args) {
604 var key, source;
605 for (var i = 1; i < arguments.length; i++) {
606 source = arguments[i];
607 for (key in source) {
608 target[key] = source[key];
609 }
610
611 // For IE the for-in-loop does not contain any properties that are not
612 // enumerable on the prototype object (for example isPrototypeOf from
613 // Object.prototype) and it will also not include 'replace' on objects that
614 // extend String and change 'replace' (not that it is common for anyone to
615 // extend anything except Object).
616
617 for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {
618 key = goog.object.PROTOTYPE_FIELDS_[j];
619 if (Object.prototype.hasOwnProperty.call(source, key)) {
620 target[key] = source[key];
621 }
622 }
623 }
624 };
625
626
627 /**
628 * Creates a new object built from the key-value pairs provided as arguments.
629 * @param {...*} var_args If only one argument is provided and it is an array
630 * then this is used as the arguments, otherwise even arguments are used as
631 * the property names and odd arguments are used as the property values.
632 * @return {!Object} The new object.
633 * @throws {Error} If there are uneven number of arguments or there is only one
634 * non array argument.
635 */
636 goog.object.create = function(var_args) {
637 var argLength = arguments.length;
638 if (argLength == 1 && goog.isArray(arguments[0])) {
639 return goog.object.create.apply(null, arguments[0]);
640 }
641
642 if (argLength % 2) {
643 throw new Error('Uneven number of arguments');
644 }
645
646 var rv = {};
647 for (var i = 0; i < argLength; i += 2) {
648 rv[arguments[i]] = arguments[i + 1];
649 }
650 return rv;
651 };
652
653
654 /**
655 * Creates a new object where the property names come from the arguments but
656 * the value is always set to true
657 * @param {...*} var_args If only one argument is provided and it is an array
658 * then this is used as the arguments, otherwise the arguments are used
659 * as the property names.
660 * @return {!Object} The new object.
661 */
662 goog.object.createSet = function(var_args) {
663 var argLength = arguments.length;
664 if (argLength == 1 && goog.isArray(arguments[0])) {
665 return goog.object.createSet.apply(null, arguments[0]);
666 }
667
668 var rv = {};
669 for (var i = 0; i < argLength; i++) {
670 rv[arguments[i]] = true;
671 }
672 return rv;
673 };
674
675
676 /**
677 * Creates an immutable view of the underlying object, if the browser
678 * supports immutable objects.
679 *
680 * In default mode, writes to this view will fail silently. In strict mode,
681 * they will throw an error.
682 *
683 * @param {!Object<K,V>} obj An object.
684 * @return {!Object<K,V>} An immutable view of that object, or the
685 * original object if this browser does not support immutables.
686 * @template K,V
687 */
688 goog.object.createImmutableView = function(obj) {
689 var result = obj;
690 if (Object.isFrozen && !Object.isFrozen(obj)) {
691 result = Object.create(obj);
692 Object.freeze(result);
693 }
694 return result;
695 };
696
697
698 /**
699 * @param {!Object} obj An object.
700 * @return {boolean} Whether this is an immutable view of the object.
701 */
702 goog.object.isImmutableView = function(obj) {
703 return !!Object.isFrozen && Object.isFrozen(obj);
704 };
705
706
707 /**
708 * Get all properties names on a given Object regardless of enumerability.
709 *
710 * <p> If the browser does not support {@code Object.getOwnPropertyNames} nor
711 * {@code Object.getPrototypeOf} then this is equivalent to using {@code
712 * goog.object.getKeys}
713 *
714 * @param {?Object} obj The object to get the properties of.
715 * @param {boolean=} opt_includeObjectPrototype Whether properties defined on
716 * {@code Object.prototype} should be included in the result.
717 * @param {boolean=} opt_includeFunctionPrototype Whether properties defined on
718 * {@code Function.prototype} should be included in the result.
719 * @return {!Array<string>}
720 * @public
721 */
722 goog.object.getAllPropertyNames = function(
723 obj, opt_includeObjectPrototype, opt_includeFunctionPrototype) {
724 if (!obj) {
725 return [];
726 }
727
728 // Naively use a for..in loop to get the property names if the browser doesn't
729 // support any other APIs for getting it.
730 if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {
731 return goog.object.getKeys(obj);
732 }
733
734 var visitedSet = {};
735
736 // Traverse the prototype chain and add all properties to the visited set.
737 var proto = obj;
738 while (proto &&
739 (proto !== Object.prototype || !!opt_includeObjectPrototype) &&
740 (proto !== Function.prototype || !!opt_includeFunctionPrototype)) {
741 var names = Object.getOwnPropertyNames(proto);
742 for (var i = 0; i < names.length; i++) {
743 visitedSet[names[i]] = true;
744 }
745 proto = Object.getPrototypeOf(proto);
746 }
747
748 return goog.object.getKeys(visitedSet);
749 };