This repository has been archived by the owner on Apr 21, 2021. It is now read-only.
/
senna.js
11717 lines (10138 loc) · 303 KB
/
senna.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
/**
* Senna.js - A blazing-fast Single Page Application engine
* @author Liferay, Inc.
* @version v2.7.9
* @link http://sennajs.com
* @license BSD-3-Clause
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.senna = {})));
}(this, (function (exports) { 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
/**
* Unique id property prefix.
* @type {String}
* @protected
*/
/**
* When defining a class Foo with an abstract method bar(), you can do:
* Foo.prototype.bar = abstractMethod
*
* Now if a subclass of Foo fails to override bar(), an error will be thrown
* when bar() is invoked.
*
* @type {!Function}
* @throws {Error} when invoked to indicate the method should be overridden.
*/
/**
* Disables Metal.js's compatibility mode.
*/
/**
* Enables Metal.js's compatibility mode with the following features from rc
* and 1.x versions:
* - Using "key" to reference component instances. In the current version
* this should be done via "ref" instead. This allows old code still
* using "key" to keep working like before. NOTE: this may cause
* problems, since "key" is meant to be used differently. Only use this
* if it's not possible to upgrade the code to use "ref" instead.
* @param {Object=} data Optional object with data to specify more
* details, such as:
* - renderers {Array} the template renderers that should be in
* compatibility mode, either their constructors or strings
* representing them (e.g. 'soy' or 'jsx'). By default, all the ones
* that extend from IncrementalDomRenderer.
* @type {Object}
*/
/**
* Returns the data used for compatibility mode, or nothing if it hasn't been
* enabled.
* @return {Object}
*/
/**
* Gets the name of the given function. If the current browser doesn't
* support the `name` property, like IE11, this will calculate it from the function's
* content string.
* @param {!function()} fn
* @return {string}
*/
/**
* Gets the value of a static property in the given class. The value will be
* inherited from ancestors as expected, unless a custom merge function is given,
* which can change how the super classes' value for that property will be merged
* together.
* The final merged value will be stored in another property, so that it won't
* be recalculated even if this function is called multiple times.
* @param {!function()} ctor Class constructor.
* @param {string} propertyName Property name to be merged.
* @param {function(*, *):*=} mergeFn Function that receives the merged
* value of the property so far and the next value to be merged to it.
* Should return these two merged together. If not passed the final property
* will be the first truthy value among ancestors.
* @return {Object}
*/
/**
* Gets an unique id. If `object` argument is passed, the object is
* mutated with an unique id. Consecutive calls with the same object
* reference won't mutate the object again, instead the current object uid
* returns. See {@link UID_PROPERTY}.
* @param {Object=} object Optional object to be mutated with the uid. If
* not specified this method only returns the uid.
* @param {boolean=} noInheritance Optional flag indicating if this
* object's uid property can be inherited from parents or not.
* @throws {Error} when invoked to indicate the method should be overridden.
* @return {number}
*/
/**
* The identity function. Returns its first argument.
* @param {*=} returnValue The single value that will be returned.
* @return {?} The first argument.
*/
/**
* Returns true if the specified value is a boolean.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is boolean.
*/
/**
* Returns true if the specified value is not undefined.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is defined.
*/
function isDef(val) {
return val !== undefined;
}
/**
* Returns true if value is not undefined or null.
* @param {*} val
* @return {boolean}
*/
function isDefAndNotNull(val) {
return isDef(val) && !isNull(val);
}
/**
* Returns true if value is a document.
* @param {*} val
* @return {boolean}
*/
function isDocument(val) {
return val && (typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && val.nodeType === 9;
}
/**
* Returns true if value is a document-fragment.
* @param {*} val
* @return {boolean}
*/
/**
* Returns true if value is a dom element.
* @param {*} val
* @return {boolean}
*/
/**
* Returns true if the specified value is a function.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is a function.
*/
function isFunction(val) {
return typeof val === 'function';
}
/**
* Returns true if value is null.
* @param {*} val
* @return {boolean}
*/
function isNull(val) {
return val === null;
}
/**
* Returns true if the specified value is a number.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is a number.
*/
/**
* Returns true if value is a window.
* @param {*} val
* @return {boolean}
*/
/**
* 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.
*/
function isObject(val) {
var type = typeof val === 'undefined' ? 'undefined' : _typeof(val);
return type === 'object' && val !== null || type === 'function';
}
/**
* Returns true if value is a Promise.
* @param {*} val
* @return {boolean}
*/
/**
* Returns true if value is a string.
* @param {*} val
* @return {boolean}
*/
function isString(val) {
return typeof val === 'string' || val instanceof String;
}
/**
* Sets to true if running inside Node.js environment with extra check for
* `process.browser` to skip Karma runner environment. Karma environment has
* `process` defined even though it runs on the browser.
* @param {?Object} options Contains `checkEnv` property which if true, checks
* the NODE_ENV variable. If NODE_ENV equals 'test', the function returns false.
* @return {boolean}
*/
function isServerSide() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { checkEnv: true };
var serverSide = typeof process !== 'undefined' && !process.browser;
if (serverSide && options.checkEnv) {
serverSide = typeof process.env !== 'undefined' && process.env.NODE_ENV !== 'test';
}
return serverSide;
}
/**
* Null function used for default values of callbacks, etc.
* @return {void} Nothing.
*/
// This file exists just for backwards compatibility, making sure that old
// default imports for this file still work. It's best to use the named exports
// for each function instead though, since that allows bundlers like Rollup to
// reduce the bundle size by removing unused code.
/**
* Set of utilities for array operations
*/
var array = function () {
function array() {
classCallCheck(this, array);
}
createClass(array, null, [{
key: 'equal',
/**
* Checks if the given arrays have the same content.
* @param {!Array<*>} arr1
* @param {!Array<*>} arr2
* @return {boolean}
*/
value: function equal(arr1, arr2) {
if (arr1 === arr2) {
return true;
}
if (arr1.length !== arr2.length) {
return false;
}
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
/**
* Returns the first value in the given array that isn't undefined.
* @param {!Array} arr
* @return {*}
*/
}, {
key: 'firstDefinedValue',
value: function firstDefinedValue(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== undefined) {
return arr[i];
}
}
}
/**
* Transforms the input nested array to become flat.
* @param {Array.<*|Array.<*>>} arr Nested array to flatten.
* @param {Array.<*>=} output Optional output array.
* @return {Array.<*>} Flat array.
*/
}, {
key: 'flatten',
value: function flatten(arr) {
var output = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
array.flatten(arr[i], output);
} else {
output.push(arr[i]);
}
}
return output;
}
/**
* Removes the first occurrence of a particular value from an array.
* @param {Array.<T>} arr Array from which to remove value.
* @param {T} obj Object to remove.
* @return {boolean} True if an element was removed.
* @template T
*/
}, {
key: 'remove',
value: function remove(arr, obj) {
var i = arr.indexOf(obj);
var rv = void 0;
if (rv = i >= 0) {
array.removeAt(arr, i);
}
return rv;
}
/**
* Removes from an array the element at index i
* @param {Array} arr Array or array like object from which to remove value.
* @param {number} i The index to remove.
* @return {boolean} True if an element was removed.
*/
}, {
key: 'removeAt',
value: function removeAt(arr, i) {
return Array.prototype.splice.call(arr, i, 1).length === 1;
}
/**
* Slices the given array, just like Array.prototype.slice, but this
* is faster and working on all array-like objects (like arguments).
* @param {!Object} arr Array-like object to slice.
* @param {number} start The index that should start the slice.
* @param {number=} end The index where the slice should end, not
* included in the final array. If not given, all elements after the
* start index will be included.
* @return {!Array}
*/
}, {
key: 'slice',
value: function slice(arr, start) {
var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
var sliced = [];
for (var i = start; i < end; i++) {
sliced.push(arr[i]);
}
return sliced;
}
}]);
return array;
}();
/* !
* Polyfill from Google's Closure Library.
* Copyright 2013 The Closure Library Authors. All Rights Reserved.
*/
var async = {};
/**
* Throw an item without interrupting the current execution context. For
* example, if processing a group of items in a loop, sometimes it is useful
* to report an error while still allowing the rest of the batch to be
* processed.
* @param {*} exception
*/
async.throwException = function (exception) {
// Each throw needs to be in its own context.
async.nextTick(function () {
throw exception;
});
};
/**
* Fires the provided callback just before the current callstack unwinds, or as
* soon as possible after the current JS execution context.
* @param {function(this:THIS)} callback
* @param {THIS=} context Object to use as the "this value" when calling
* the provided function.
* @template THIS
*/
async.run = function (callback, context) {
if (!async.run.workQueueScheduled_) {
// Nothing is currently scheduled, schedule it now.
async.nextTick(async.run.processWorkQueue);
async.run.workQueueScheduled_ = true;
}
async.run.workQueue_.push(new async.run.WorkItem_(callback, context));
};
/** @private {boolean} */
async.run.workQueueScheduled_ = false;
/** @private {!Array.<!async.run.WorkItem_>} */
async.run.workQueue_ = [];
/**
* Run any pending async.run work items. This function is not intended
* for general use, but for use by entry point handlers to run items ahead of
* async.nextTick.
*/
async.run.processWorkQueue = function () {
// NOTE: additional work queue items may be pushed while processing.
while (async.run.workQueue_.length) {
// Don't let the work queue grow indefinitely.
var workItems = async.run.workQueue_;
async.run.workQueue_ = [];
for (var i = 0; i < workItems.length; i++) {
var workItem = workItems[i];
try {
workItem.fn.call(workItem.scope);
} catch (e) {
async.throwException(e);
}
}
}
// There are no more work items, reset the work queue.
async.run.workQueueScheduled_ = false;
};
/**
* @constructor
* @final
* @struct
* @private
*
* @param {function()} fn
* @param {Object|null|undefined} scope
*/
async.run.WorkItem_ = function (fn, scope) {
/** @const */
this.fn = fn;
/** @const */
this.scope = scope;
};
/**
* Fires the provided callbacks as soon as possible after the current JS
* execution context. setTimeout(…, 0) always takes at least 5ms for legacy
* reasons.
* @param {function(this:SCOPE)} callback Callback function to fire as soon as
* possible.
* @param {SCOPE=} context Object in whose scope to call the listener.
* @template SCOPE
*/
async.nextTick = function (callback, context) {
var cb = callback;
if (context) {
cb = callback.bind(context);
}
cb = async.nextTick.wrapCallback_(cb);
// Look for and cache the custom fallback version of setImmediate.
if (!async.nextTick.setImmediate_) {
if (typeof setImmediate === 'function' && isServerSide({ checkEnv: false })) {
async.nextTick.setImmediate_ = setImmediate;
} else {
// eslint-disable-next-line
async.nextTick.setImmediate_ = async.nextTick.getSetImmediateEmulator_();
}
}
async.nextTick.setImmediate_(cb);
};
/**
* Cache for the setImmediate implementation.
* @type {function(function())}
* @private
*/
async.nextTick.setImmediate_ = null;
/**
* Determines the best possible implementation to run a function as soon as
* the JS event loop is idle.
* @return {function(function())} The "setImmediate" implementation.
* @private
*/
async.nextTick.getSetImmediateEmulator_ = function () {
// Create a private message channel and use it to postMessage empty messages
// to ourselves.
var Channel = void 0;
// Verify if variable is defined on the current runtime (i.e., node, browser).
// Can't use typeof enclosed in a function (such as core.isFunction) or an
// exception will be thrown when the function is called on an environment
// where the variable is undefined.
if (typeof MessageChannel === 'function') {
Channel = MessageChannel;
}
// If MessageChannel is not available and we are in a browser, implement
// an iframe based polyfill in browsers that have postMessage and
// document.addEventListener. The latter excludes IE8 because it has a
// synchronous postMessage implementation.
if (typeof Channel === 'undefined' && typeof window !== 'undefined' && window.postMessage && window.addEventListener) {
/** @constructor */
Channel = function Channel() {
// Make an empty, invisible iframe.
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = '';
iframe.title = '';
document.documentElement.appendChild(iframe);
var win = iframe.contentWindow;
var doc = win.document;
doc.open();
doc.write('');
doc.close();
var message = 'callImmediate' + Math.random();
var origin = win.location.protocol + '//' + win.location.host;
var onmessage = function (e) {
// Validate origin and message to make sure that this message was
// intended for us.
if (e.origin !== origin && e.data !== message) {
return;
}
this.port1.onmessage();
}.bind(this);
win.addEventListener('message', onmessage, false);
this.port1 = {};
this.port2 = {
postMessage: function postMessage() {
win.postMessage(message, origin);
}
};
};
}
if (typeof Channel !== 'undefined') {
var channel = new Channel();
// Use a fifo linked list to call callbacks in the right order.
var head = {};
var tail = head;
channel.port1.onmessage = function () {
head = head.next;
var cb = head.cb;
head.cb = null;
cb();
};
return function (cb) {
tail.next = {
cb: cb
};
tail = tail.next;
channel.port2.postMessage(0);
};
}
// Implementation for IE6-8: Script elements fire an asynchronous
// onreadystatechange event when inserted into the DOM.
if (typeof document !== 'undefined' && 'onreadystatechange' in document.createElement('script')) {
return function (cb) {
var script = document.createElement('script');
script.onreadystatechange = function () {
// Clean up and call the callback.
script.onreadystatechange = null;
script.parentNode.removeChild(script);
script = null;
cb();
cb = null;
};
document.documentElement.appendChild(script);
};
}
// Fall back to setTimeout with 0. In browsers this creates a delay of 5ms
// or more.
return function (cb) {
setTimeout(cb, 0);
};
};
/**
* Helper function that is overrided to protect callbacks with entry point
* monitor if the application monitors entry points.
* @param {function()} callback Callback function to fire as soon as possible.
* @return {function()} The wrapped callback.
* @private
*/
async.nextTick.wrapCallback_ = function (callback) {
return callback;
};
/**
* Disposable utility. When inherited provides the `dispose` function to its
* subclass, which is responsible for disposing of any object references
* when an instance won't be used anymore. Subclasses should override
* `disposeInternal` to implement any specific disposing logic.
* @constructor
*/
var Disposable = function () {
/**
* Disposable constructor
*/
function Disposable() {
classCallCheck(this, Disposable);
/**
* Flag indicating if this instance has already been disposed.
* @type {boolean}
* @protected
*/
this.disposed_ = false;
}
/**
* Disposes of this instance's object references. Calls `disposeInternal`.
*/
createClass(Disposable, [{
key: 'dispose',
value: function dispose() {
if (!this.disposed_) {
this.disposeInternal();
this.disposed_ = true;
}
}
/**
* Subclasses should override this method to implement any specific
* disposing logic (like clearing references and calling `dispose` on other
* disposables).
*/
}, {
key: 'disposeInternal',
value: function disposeInternal() {}
/**
* Checks if this instance has already been disposed.
* @return {boolean}
*/
}, {
key: 'isDisposed',
value: function isDisposed() {
return this.disposed_;
}
}]);
return Disposable;
}();
/**
* Set of utilities for object operations
*/
var object = function () {
function object() {
classCallCheck(this, object);
}
createClass(object, null, [{
key: 'mixin',
/**
* Copies all the members of a source object to a target object.
* @param {Object} target Target object.
* @param {...Object} var_args The objects from which values will be copied.
* @return {Object} Returns the target object reference.
*/
value: function mixin(target) {
var key = void 0;
var source = void 0;
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
for (var i = 0; i < args.length; i++) {
source = args[i];
// Possible prototype chain leak, breaks 1 metal-dom and
// 1 metal-incremental-dom test if guard-for-in rule is addressed
// eslint-disable-next-line
for (key in source) {
target[key] = source[key];
}
}
return target;
}
/**
* Returns an object based on its fully qualified external name.
* @param {string} name The fully qualified name.
* @param {object=} scope The object within which to look; default is
* <code>window</code>.
* @return {?} The value (object or primitive) or, if not found, undefined.
*/
}, {
key: 'getObjectByName',
value: function getObjectByName(name) {
var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window;
var parts = name.split('.');
return parts.reduce(function (part, key) {
return part[key];
}, scope);
}
/**
* Returns a new object with the same keys as the given one, but with
* their values set to the return values of the specified function.
* @param {!Object} obj
* @param {!function(string, *)} fn
* @return {!Object}
*/
}, {
key: 'map',
value: function map(obj, fn) {
var mappedObj = {};
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
mappedObj[keys[i]] = fn(keys[i], obj[keys[i]]);
}
return mappedObj;
}
/**
* Checks if the two given objects are equal. This is done via a shallow
* check, including only the keys directly contained by the 2 objects.
* @param {Object} obj1
* @param {Object} obj2
* @return {boolean}
*/
}, {
key: 'shallowEqual',
value: function shallowEqual(obj1, obj2) {
if (obj1 === obj2) {
return true;
}
var keys1 = Object.keys(obj1);
var keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (var i = 0; i < keys1.length; i++) {
if (obj1[keys1[i]] !== obj2[keys1[i]]) {
return false;
}
}
return true;
}
}]);
return object;
}();
/**
* Set of utilities for string operations
*/
var string = function () {
function string() {
classCallCheck(this, string);
}
createClass(string, null, [{
key: 'caseInsensitiveCompare',
/**
* Compares the given strings without taking the case into account.
* @param {string|number} str1
* @param {string|number} str2
* @return {number} Either -1, 0 or 1, according to if the first string is
* "smaller", equal or "bigger" than the second given string.
*/
value: function caseInsensitiveCompare(str1, str2) {
var test1 = String(str1).toLowerCase();
var test2 = String(str2).toLowerCase();
if (test1 < test2) {
return -1;
} else if (test1 === test2) {
return 0;
} else {
return 1;
}
}
/**
* Removes the breaking spaces from the left and right of the string and
* collapses the sequences of breaking spaces in the middle into single spaces.
* The original and the result strings render the same way in HTML.
* @param {string} str A string in which to collapse spaces.
* @return {string} Copy of the string with normalized breaking spaces.
*/
}, {
key: 'collapseBreakingSpaces',
value: function collapseBreakingSpaces(str) {
return str.replace(/[\t\r\n ]+/g, ' ').replace(/^[\t\r\n ]+|[\t\r\n ]+$/g, '');
}
/**
* Escapes characters in the string that are not safe to use in a RegExp.
* @param {*} str The string to escape. If not a string, it will be casted
* to one.
* @return {string} A RegExp safe, escaped copy of {@code s}.
*/
}, {
key: 'escapeRegex',
value: function escapeRegex(str) {
return String(str).replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08'); // eslint-disable-line
}
/**
* Returns a string with at least 64-bits of randomness.
* @return {string} A random string, e.g. sn1s7vb4gcic.
*/
}, {
key: 'getRandomString',
value: function getRandomString() {
var x = 2147483648;
return Math.floor(Math.random() * x).toString(36) + Math.abs(Math.floor(Math.random() * x) ^ Date.now()).toString(36);
}
/**
* Calculates the hashcode for a string. The hashcode value is computed by
* the sum algorithm: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]. A nice
* property of using 31 prime is that the multiplication can be replaced by
* a shift and a subtraction for better performance: 31*i == (i<<5)-i.
* Modern VMs do this sort of optimization automatically.
* @param {String} val Target string.
* @return {Number} Returns the string hashcode.
*/
}, {