-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.js
1319 lines (1151 loc) · 41.4 KB
/
base.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Bootstrap for the Google JS Library (Closure).
*
* In uncompiled mode base.js will write out Closure's deps file, unless the
* global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to
* include their own deps file(s) from different locations.
*
*
*
*/
/**
* @define {boolean} Overridden to true by the compiler when --closure_pass
* or --mark_as_compiled is specified.
*/
var COMPILED = false;
/**
* Base namespace for the Closure library. Checks to see goog is
* already defined in the current scope before assigning to prevent
* clobbering if base.js is loaded more than once.
*/
var goog = goog || {}; // Check to see if already defined in current scope
/**
* Reference to the global context. In most cases this will be 'window'.
*/
goog.global = this;
/**
* @define {boolean} DEBUG is provided as a convenience so that debugging code
* that should not be included in a production js_binary can be easily stripped
* by specifying --define goog.DEBUG=false to the JSCompiler. For example, most
* toString() methods should be declared inside an "if (goog.DEBUG)" conditional
* because they are generally used for debugging purposes and it is difficult
* for the JSCompiler to statically determine whether they are used.
*/
goog.DEBUG = true;
/**
* @define {string} LOCALE defines the locale being used for compilation. It is
* used to select locale specific data to be compiled in js binary. BUILD rule
* can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler
* option.
*
* Take into account that the locale code format is important. You should use
* the canonical Unicode format with hyphen as a delimiter. Language must be
* lowercase, Language Script - Capitalized, Region - UPPERCASE.
* There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.
*
* See more info about locale codes here:
* http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers
*
* For language codes you should use values defined by ISO 693-1. See it here
* http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from
* this rule: the Hebrew language. For legacy reasons the old code (iw) should
* be used instead of the new code (he), see http://wiki/Main/IIISynonyms.
*/
goog.LOCALE = 'en'; // default to en
/**
* Indicates whether or not we can call 'eval' directly to eval code in the
* global scope. Set to a Boolean by the first call to goog.globalEval (which
* empirically tests whether eval works for globals). @see goog.globalEval
* @type {?boolean}
* @private
*/
goog.evalWorksForGlobals_ = null;
/**
* Creates object stubs for a namespace. When present in a file, goog.provide
* also indicates that the file defines the indicated object. Calls to
* goog.provide are resolved by the compiler if --closure_pass is set.
* @param {string} name name of the object that this file defines.
*/
goog.provide = function(name) {
if (!COMPILED) {
// Ensure that the same namespace isn't provided twice. This is intended
// to teach new developers that 'goog.provide' is effectively a variable
// declaration. And when JSCompiler transforms goog.provide into a real
// variable declaration, the compiled JS should work the same as the raw
// JS--even when the raw JS uses goog.provide incorrectly.
if (goog.getObjectByName(name) && !goog.implicitNamespaces_[name]) {
throw Error('Namespace "' + name + '" already declared.');
}
var namespace = name;
while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {
goog.implicitNamespaces_[namespace] = true;
}
}
goog.exportPath_(name);
};
if (!COMPILED) {
/**
* Namespaces implicitly defined by goog.provide. For example,
* goog.provide('goog.events.Event') implicitly declares
* that 'goog' and 'goog.events' must be namespaces.
*
* @type {Object}
* @private
*/
goog.implicitNamespaces_ = {};
}
/**
* Builds an object structure for the provided namespace path,
* ensuring that names that already exist are not overwritten. For
* example:
* "a.b.c" -> a = {};a.b={};a.b.c={};
* Used by goog.provide and goog.exportSymbol.
* @param {string} name name of the object that this file defines.
* @param {*=} opt_object the object to expose at the end of the path.
* @param {Object=} opt_objectToExportTo The object to add the path to; default
* is |goog.global|.
* @private
*/
goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
var parts = name.split('.');
var cur = opt_objectToExportTo || goog.global;
// Internet Explorer exhibits strange behavior when throwing errors from
// methods externed in this manner. See the testExportSymbolExceptions in
// base_test.html for an example.
if (!(parts[0] in cur) && cur.execScript) {
cur.execScript('var ' + parts[0]);
}
// Certain browsers cannot parse code in the form for((a in b); c;);
// This pattern is produced by the JSCompiler when it collapses the
// statement above into the conditional loop below. To prevent this from
// happening, use a for-loop and reserve the init logic as below.
// Parentheses added to eliminate strict JS warning in Firefox.
for (var part; parts.length && (part = parts.shift());) {
if (!parts.length && goog.isDef(opt_object)) {
// last part and we have an object; use it
cur[part] = opt_object;
} else if (cur[part]) {
cur = cur[part];
} else {
cur = cur[part] = {};
}
}
};
/**
* Returns an object based on its fully qualified external name. If you are
* using a compilation pass that renames property names beware that using this
* function will not find renamed properties.
*
* @param {string} name The fully qualified name.
* @param {Object=} opt_obj The object within which to look; default is
* |goog.global|.
* @return {Object} The object or, if not found, null.
*/
goog.getObjectByName = function(name, opt_obj) {
var parts = name.split('.');
var cur = opt_obj || goog.global;
for (var part; part = parts.shift(); ) {
if (cur[part]) {
cur = cur[part];
} else {
return null;
}
}
return cur;
};
/**
* Globalizes a whole namespace, such as goog or goog.lang.
*
* @param {Object} obj The namespace to globalize.
* @param {Object=} opt_global The object to add the properties to.
* @deprecated Properties may be explicitly exported to the global scope, but
* this should no longer be done in bulk.
*/
goog.globalize = function(obj, opt_global) {
var global = opt_global || goog.global;
for (var x in obj) {
global[x] = obj[x];
}
};
/**
* Adds a dependency from a file to the files it requires.
* @param {string} relPath The path to the js file.
* @param {Array} provides An array of strings with the names of the objects
* this file provides.
* @param {Array} requires An array of strings with the names of the objects
* this file requires.
*/
goog.addDependency = function(relPath, provides, requires) {
if (!COMPILED) {
var provide, require;
var path = relPath.replace(/\\/g, '/');
var deps = goog.dependencies_;
for (var i = 0; provide = provides[i]; i++) {
deps.nameToPath[provide] = path;
if (!(path in deps.pathToNames)) {
deps.pathToNames[path] = {};
}
deps.pathToNames[path][provide] = true;
}
for (var j = 0; require = requires[j]; j++) {
if (!(path in deps.requires)) {
deps.requires[path] = {};
}
deps.requires[path][require] = true;
}
}
};
/**
* Implements a system for the dynamic resolution of dependencies
* that works in parallel with the BUILD system. Note that all calls
* to goog.require will be stripped by the JSCompiler when the
* --closure_pass option is used.
* @param {string} rule Rule to include, in the form goog.package.part.
*/
goog.require = function(rule) {
// if the object already exists we do not need do do anything
// TODO(user): If we start to support require based on file name this has
// to change
// TODO(user): If we allow goog.foo.* this has to change
// TODO(user): If we implement dynamic load after page load we should probably
// not remove this code for the compiled output
if (!COMPILED) {
if (goog.getObjectByName(rule)) {
return;
}
var path = goog.getPathFromDeps_(rule);
if (path) {
goog.included_[path] = true;
goog.writeScripts_();
} else {
var errorMessage = 'goog.require could not find: ' + rule;
if (goog.global.console) {
goog.global.console['error'](errorMessage);
}
throw Error(errorMessage);
}
}
};
/**
* Path for included scripts
* @type {string}
*/
goog.basePath = '';
/**
* A hook for overriding the base path.
* @type {string|undefined}
*/
goog.global.CLOSURE_BASE_PATH;
/**
* Whether to write out Closure's deps file. By default,
* the deps are written.
* @type {boolean|undefined}
*/
goog.global.CLOSURE_NO_DEPS;
/**
* Null function used for default values of callbacks, etc.
* @return {void} Nothing.
*/
goog.nullFunction = function() {};
/**
* The identity function. Returns its first argument.
*
* @param {...*} var_args The arguments of the function.
* @return {*} The first argument.
* @deprecated Use goog.functions.identity instead.
*/
goog.identityFunction = function(var_args) {
return arguments[0];
};
/**
* When defining a class Foo with an abstract method bar(), you can do:
*
* Foo.prototype.bar = goog.abstractMethod
*
* Now if a subclass of Foo fails to override bar(), an error
* will be thrown when bar() is invoked.
*
* Note: This does not take the name of the function to override as
* an argument because that would make it more difficult to obfuscate
* our JavaScript code.
*
* @type {!Function}
* @throws {Error} when invoked to indicate the method should be
* overridden.
*/
goog.abstractMethod = function() {
throw Error('unimplemented abstract method');
};
/**
* Adds a {@code getInstance} static method that always return the same instance
* object.
* @param {!Function} ctor The constructor for the class to add the static
* method to.
*/
goog.addSingletonGetter = function(ctor) {
ctor.getInstance = function() {
return ctor.instance_ || (ctor.instance_ = new ctor());
};
};
if (!COMPILED) {
/**
* Object used to keep track of urls that have already been added. This
* record allows the prevention of circular dependencies.
* @type {Object}
* @private
*/
goog.included_ = {};
/**
* This object is used to keep track of dependencies and other data that is
* used for loading scripts
* @private
* @type {Object}
*/
goog.dependencies_ = {
pathToNames: {}, // 1 to many
nameToPath: {}, // 1 to 1
requires: {}, // 1 to many
visited: {}, // used when resolving dependencies to prevent us from
// visiting the file twice
written: {} // used to keep track of script files we have written
};
/**
* Tries to detect whether is in the context of an HTML document.
* @return {boolean} True if it looks like HTML document.
* @private
*/
goog.inHtmlDocument_ = function() {
var doc = goog.global.document;
return typeof doc != 'undefined' &&
'write' in doc; // XULDocument misses write.
};
/**
* Tries to detect the base path of the base.js script that bootstraps Closure
* @private
*/
goog.findBasePath_ = function() {
if (!goog.inHtmlDocument_()) {
return;
}
var doc = goog.global.document;
if (goog.global.CLOSURE_BASE_PATH) {
goog.basePath = goog.global.CLOSURE_BASE_PATH;
return;
}
var scripts = doc.getElementsByTagName('script');
// Search backwards since the current script is in almost all cases the one
// that has base.js.
for (var i = scripts.length - 1; i >= 0; --i) {
var src = scripts[i].src;
var l = src.length;
if (src.substr(l - 7) == 'base.js') {
goog.basePath = src.substr(0, l - 7);
return;
}
}
};
/**
* Writes a script tag if, and only if, that script hasn't already been added
* to the document. (Must be called at execution time)
* @param {string} src Script source.
* @private
*/
goog.writeScriptTag_ = function(src) {
if (goog.inHtmlDocument_() &&
!goog.dependencies_.written[src]) {
goog.dependencies_.written[src] = true;
var doc = goog.global.document;
doc.write('<script type="text/javascript" src="' +
src + '"></' + 'script>');
}
};
/**
* Resolves dependencies based on the dependencies added using addDependency
* and calls writeScriptTag_ in the correct order.
* @private
*/
goog.writeScripts_ = function() {
// the scripts we need to write this time
var scripts = [];
var seenScript = {};
var deps = goog.dependencies_;
function visitNode(path) {
if (path in deps.written) {
return;
}
// we have already visited this one. We can get here if we have cyclic
// dependencies
if (path in deps.visited) {
if (!(path in seenScript)) {
seenScript[path] = true;
scripts.push(path);
}
return;
}
deps.visited[path] = true;
if (path in deps.requires) {
for (var requireName in deps.requires[path]) {
if (requireName in deps.nameToPath) {
visitNode(deps.nameToPath[requireName]);
} else if (!goog.getObjectByName(requireName)) {
// If the required name is defined, we assume that this
// dependency was bootstapped by other means. Otherwise,
// throw an exception.
throw Error('Undefined nameToPath for ' + requireName);
}
}
}
if (!(path in seenScript)) {
seenScript[path] = true;
scripts.push(path);
}
}
for (var path in goog.included_) {
if (!deps.written[path]) {
visitNode(path);
}
}
for (var i = 0; i < scripts.length; i++) {
if (scripts[i]) {
goog.writeScriptTag_(goog.basePath + scripts[i]);
} else {
throw Error('Undefined script input');
}
}
};
/**
* Looks at the dependency rules and tries to determine the script file that
* fulfills a particular rule.
* @param {string} rule In the form goog.namespace.Class or project.script.
* @return {?string} Url corresponding to the rule, or null.
* @private
*/
goog.getPathFromDeps_ = function(rule) {
if (rule in goog.dependencies_.nameToPath) {
return goog.dependencies_.nameToPath[rule];
} else {
return null;
}
};
goog.findBasePath_();
// Allow projects to manage the deps files themselves.
if (!goog.global.CLOSURE_NO_DEPS) {
goog.writeScriptTag_(goog.basePath + 'deps.js');
}
}
//==============================================================================
// Language Enhancements
//==============================================================================
/**
* This is a "fixed" version of the typeof operator. It differs from the typeof
* operator in such a way that null returns 'null' and arrays return 'array'.
* @param {*} value The value to get the type of.
* @return {string} The name of the type.
*/
goog.typeOf = function(value) {
var s = typeof value;
if (s == 'object') {
if (value) {
// We cannot use constructor == Array or instanceof Array because
// different frames have different Array objects. In IE6, if the iframe
// where the array was created is destroyed, the array loses its
// prototype. Then dereferencing val.splice here throws an exception, so
// we can't use goog.isFunction. Calling typeof directly returns 'unknown'
// so that will work. In this case, this function will return false and
// most array functions will still work because the array is still
// array-like (supports length and []) even though it has lost its
// prototype.
// Mark Miller noticed that Object.prototype.toString
// allows access to the unforgeable [[Class]] property.
// 15.2.4.2 Object.prototype.toString ( )
// When the toString method is called, the following steps are taken:
// 1. Get the [[Class]] property of this object.
// 2. Compute a string value by concatenating the three strings
// "[object ", Result(1), and "]".
// 3. Return Result(2).
// and this behavior survives the destruction of the execution context.
if (value instanceof Array || // Works quickly in same execution context.
// If value is from a different execution context then
// !(value instanceof Object), which lets us early out in the common
// case when value is from the same context but not an array.
// The {if (value)} check above means we don't have to worry about
// undefined behavior of Object.prototype.toString on null/undefined.
//
// HACK: In order to use an Object prototype method on the arbitrary
// value, the compiler requires the value be cast to type Object,
// even though the ECMA spec explicitly allows it.
(!(value instanceof Object) &&
(Object.prototype.toString.call(
/** @type {Object} */ (value)) == '[object Array]') ||
// In IE all non value types are wrapped as objects across window
// boundaries (not iframe though) so we have to do object detection
// for this edge case
typeof value.length == 'number' &&
typeof value.splice != 'undefined' &&
typeof value.propertyIsEnumerable != 'undefined' &&
!value.propertyIsEnumerable('splice')
)) {
return 'array';
}
// HACK: There is still an array case that fails.
// function ArrayImpostor() {}
// ArrayImpostor.prototype = [];
// var impostor = new ArrayImpostor;
// this can be fixed by getting rid of the fast path
// (value instanceof Array) and solely relying on
// (value && Object.prototype.toString.vall(value) === '[object Array]')
// but that would require many more function calls and is not warranted
// unless closure code is receiving objects from untrusted sources.
// IE in cross-window calls does not correctly marshal the function type
// (it appears just as an object) so we cannot use just typeof val ==
// 'function'. However, if the object has a call property, it is a
// function.
if (!(value instanceof Object) &&
(Object.prototype.toString.call(
/** @type {Object} */ (value)) == '[object Function]' ||
typeof value.call != 'undefined' &&
typeof value.propertyIsEnumerable != 'undefined' &&
!value.propertyIsEnumerable('call'))) {
return 'function';
}
} else {
return 'null';
}
} else if (s == 'function' && typeof value.call == 'undefined') {
// In Safari typeof nodeList returns 'function', and on Firefox
// typeof behaves similarly for HTML{Applet,Embed,Object}Elements
// and RegExps. We would like to return object for those and we can
// detect an invalid function by making sure that the function
// object has a call method.
return 'object';
}
return s;
};
/**
* Safe way to test whether a property is enumarable. It allows testing
* for enumerable on objects where 'propertyIsEnumerable' is overridden or
* does not exist (like DOM nodes in IE). Does not use browser native
* Object.propertyIsEnumerable.
* @param {Object} object The object to test if the property is enumerable.
* @param {string} propName The property name to check for.
* @return {boolean} True if the property is enumarable.
* @private
*/
goog.propertyIsEnumerableCustom_ = function(object, propName) {
// KJS in Safari 2 is not ECMAScript compatible and lacks crucial methods
// such as propertyIsEnumerable. We therefore use a workaround.
// Does anyone know a more efficient work around?
if (propName in object) {
for (var key in object) {
if (key == propName &&
Object.prototype.hasOwnProperty.call(object, propName)) {
return true;
}
}
}
return false;
};
/**
* Safe way to test whether a property is enumarable. It allows testing
* for enumerable on objects where 'propertyIsEnumerable' is overridden or
* does not exist (like DOM nodes in IE).
* @param {Object} object The object to test if the property is enumerable.
* @param {string} propName The property name to check for.
* @return {boolean} True if the property is enumarable.
* @private
*/
goog.propertyIsEnumerable_ = function(object, propName) {
// In IE if object is from another window, cannot use propertyIsEnumerable
// from this window's Object. Will raise a 'JScript object expected' error.
if (object instanceof Object) {
return Object.prototype.propertyIsEnumerable.call(object, propName);
} else {
return goog.propertyIsEnumerableCustom_(object, propName);
}
};
/**
* Returns true if the specified value is not |undefined|.
* WARNING: Do not use this to test if an object has a property. Use the in
* operator instead. Additionally, this function assumes that the global
* undefined variable has not been redefined.
* @param {*} val Variable to test.
* @return {boolean} Whether variable is defined.
*/
goog.isDef = function(val) {
return val !== undefined;
};
/**
* Returns true if the specified value is |null|
* @param {*} val Variable to test.
* @return {boolean} Whether variable is null.
*/
goog.isNull = function(val) {
return val === null;
};
/**
* Returns true if the specified value is defined and not null
* @param {*} val Variable to test.
* @return {boolean} Whether variable is defined and not null.
*/
goog.isDefAndNotNull = function(val) {
// Note that undefined == null.
return val != null;
};
/**
* Returns true if the specified value is an array
* @param {*} val Variable to test.
* @return {boolean} Whether variable is an array.
*/
goog.isArray = function(val) {
return goog.typeOf(val) == 'array';
};
/**
* Returns true if the object looks like an array. To qualify as array like
* the value needs to be either a NodeList or an object with a Number length
* property.
* @param {*} val Variable to test.
* @return {boolean} Whether variable is an array.
*/
goog.isArrayLike = function(val) {
var type = goog.typeOf(val);
return type == 'array' || type == 'object' && typeof val.length == 'number';
};
/**
* Returns true if the object looks like a Date. To qualify as Date-like
* the value needs to be an object and have a getFullYear() function.
* @param {*} val Variable to test.
* @return {boolean} Whether variable is a like a Date.
*/
goog.isDateLike = function(val) {
return goog.isObject(val) && typeof val.getFullYear == 'function';
};
/**
* Returns true if the specified value is a string
* @param {*} val Variable to test.
* @return {boolean} Whether variable is a string.
*/
goog.isString = function(val) {
return typeof val == 'string';
};
/**
* Returns true if the specified value is a boolean
* @param {*} val Variable to test.
* @return {boolean} Whether variable is boolean.
*/
goog.isBoolean = function(val) {
return typeof val == 'boolean';
};
/**
* Returns true if the specified value is a number
* @param {*} val Variable to test.
* @return {boolean} Whether variable is a number.
*/
goog.isNumber = function(val) {
return typeof val == 'number';
};
/**
* Returns true if the specified value is a function
* @param {*} val Variable to test.
* @return {boolean} Whether variable is a function.
*/
goog.isFunction = function(val) {
return goog.typeOf(val) == 'function';
};
/**
* Returns true if the specified value is an object. This includes arrays
* and functions.
* @param {*} val Variable to test.
* @return {boolean} Whether variable is an object.
*/
goog.isObject = function(val) {
var type = goog.typeOf(val);
return type == 'object' || type == 'array' || type == 'function';
};
/**
* Gets a unique ID for an object. This mutates the object so that further
* calls with the same object as a parameter returns the same value. The unique
* ID is guaranteed to be unique across the current session amongst objects that
* are passed into {@code getUid}. There is no guarantee that the ID is unique
* or consistent across sessions. It is unsafe to generate unique ID for
* function prototypes.
*
* @param {Object} obj The object to get the unique ID for.
* @return {number} The unique ID for the object.
*/
goog.getUid = function(obj) {
// TODO(user): Make the type stricter, do not accept null.
// In Opera window.hasOwnProperty exists but always returns false so we avoid
// using it. As a consequence the unique ID generated for BaseClass.prototype
// and SubClass.prototype will be the same.
return obj[goog.UID_PROPERTY_] ||
(obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
};
/**
* Removes the unique ID from an object. This is useful if the object was
* previously mutated using {@code goog.getUid} in which case the mutation is
* undone.
* @param {Object} obj The object to remove the unique ID field from.
*/
goog.removeUid = function(obj) {
// TODO(user): Make the type stricter, do not accept null.
// DOM nodes in IE are not instance of Object and throws exception
// for delete. Instead we try to use removeAttribute
if ('removeAttribute' in obj) {
obj.removeAttribute(goog.UID_PROPERTY_);
}
/** @preserveTry */
try {
delete obj[goog.UID_PROPERTY_];
} catch (ex) {
}
};
/**
* Name for unique ID property. Initialized in a way to help avoid collisions
* with other closure javascript on the same page.
* @type {string}
* @private
*/
goog.UID_PROPERTY_ = 'closure_uid_' +
Math.floor(Math.random() * 2147483648).toString(36);
/**
* Counter for UID.
* @type {number}
* @private
*/
goog.uidCounter_ = 0;
/**
* Adds a hash code field to an object. The hash code is unique for the
* given object.
* @param {Object} obj The object to get the hash code for.
* @return {number} The hash code for the object.
* @deprecated Use goog.getUid instead.
*/
goog.getHashCode = goog.getUid;
/**
* Removes the hash code field from an object.
* @param {Object} obj The object to remove the field from.
* @deprecated Use goog.removeUid instead.
*/
goog.removeHashCode = goog.removeUid;
/**
* Clones a value. The input may be an Object, Array, or basic type. Objects and
* arrays will be cloned recursively.
*
* WARNINGS:
* <code>goog.cloneObject</code> does not detect reference loops. Objects that
* refer to themselves will cause infinite recursion.
*
* <code>goog.cloneObject</code> is unaware of unique identifiers, and copies
* UIDs created by <code>getUid</code> into cloned results.
*
* @param {*} obj The value to clone.
* @return {*} A clone of the input value.
* @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.
*/
goog.cloneObject = function(obj) {
var type = goog.typeOf(obj);
if (type == 'object' || type == 'array') {
if (obj.clone) {
return obj.clone();
}
var clone = type == 'array' ? [] : {};
for (var key in obj) {
clone[key] = goog.cloneObject(obj[key]);
}
return clone;
}
return obj;
};
/**
* Forward declaration for the clone method. This is necessary until the
* compiler can better support duck-typing constructs as used in
* goog.cloneObject.
*
* TODO(user): Remove once the JSCompiler can infer that the check for
* proto.clone is safe in goog.cloneObject.
*
* @type {Function}
*/
Object.prototype.clone;
/**
* Partially applies this function to a particular 'this object' and zero or
* more arguments. The result is a new function with some arguments of the first
* function pre-filled and the value of |this| 'pre-specified'.<br><br>
*
* Remaining arguments specified at call-time are appended to the pre-
* specified ones.<br><br>
*
* Also see: {@link #partial}.<br><br>
*
* Usage:
* <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2');
* barMethBound('arg3', 'arg4');</pre>
*
* @param {Function} fn A function to partially apply.
* @param {Object|undefined} selfObj Specifies the object which |this| should
* point to when the function is run. If the value is null or undefined, it
* will default to the global object.
* @param {...*} var_args Additional arguments that are partially
* applied to the function.
*
* @return {!Function} A partially-applied form of the function bind() was
* invoked as a method of.
*/
goog.bind = function(fn, selfObj, var_args) {
var context = selfObj || goog.global;
if (arguments.length > 2) {
var boundArgs = Array.prototype.slice.call(arguments, 2);
return function() {
// Prepend the bound arguments to the current arguments.
var newArgs = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(newArgs, boundArgs);
return fn.apply(context, newArgs);
};
} else {
return function() {
return fn.apply(context, arguments);
};
}
};
/**
* Like bind(), except that a 'this object' is not required. Useful when the
* target function is already bound.
*
* Usage:
* var g = partial(f, arg1, arg2);
* g(arg3, arg4);
*
* @param {Function} fn A function to partially apply.
* @param {...*} var_args Additional arguments that are partially
* applied to fn.
* @return {!Function} A partially-applied form of the function bind() was
* invoked as a method of.
*/
goog.partial = function(fn, var_args) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
// Prepend the bound arguments to the current arguments.
var newArgs = Array.prototype.slice.call(arguments);
newArgs.unshift.apply(newArgs, args);
return fn.apply(this, newArgs);
};
};
/**
* Copies all the members of a source object to a target object. This method
* does not work on all browsers for all objects that contain keys such as
* toString or hasOwnProperty. Use goog.object.extend for this purpose.
* @param {Object} target Target.
* @param {Object} source Source.
*/
goog.mixin = function(target, source) {
for (var x in source) {
target[x] = source[x];
}
// For IE7 or lower, the for-in-loop does not contain any properties that are
// not enumerable on the prototype object (for example, isPrototypeOf from
// Object.prototype) but also it will not include 'replace' on objects that
// extend String and change 'replace' (not that it is common for anyone to
// extend anything except Object).
};