forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sugar-es5.js
14106 lines (12896 loc) · 418 KB
/
sugar-es5.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
/*
* Sugar v2.0.6
*
* Freely distributable and licensed under the MIT-style license.
* Copyright (c) Andrew Plummer
* https://sugarjs.com/
*
* ---------------------------- */
(function() {
'use strict';
/***
* @module Core
* @description Core functionality including the ability to define methods and
* extend onto natives.
*
***/
// The global to export.
var Sugar;
// The name of Sugar in the global namespace.
var SUGAR_GLOBAL = 'Sugar';
// Natives available on initialization. Letting Object go first to ensure its
// global is set by the time the rest are checking for chainable Object methods.
var NATIVE_NAMES = 'Object Number String Array Date RegExp Function';
// Static method flag
var STATIC = 0x1;
// Instance method flag
var INSTANCE = 0x2;
// IE8 has a broken defineProperty but no defineProperties so this saves a try/catch.
var PROPERTY_DESCRIPTOR_SUPPORT = !!(Object.defineProperty && Object.defineProperties);
var globalContext = getGlobal();
// Whether object instance methods can be mapped to the prototype.
var allowObjectPrototype = false;
// A map from Array to SugarArray.
var namespacesByName = {};
// A map from [object Object] to namespace.
var namespacesByClassString = {};
// Defining properties.
// istanbul ignore next
var defineProperty = PROPERTY_DESCRIPTOR_SUPPORT ? Object.defineProperty : definePropertyShim;
// A default chainable class for unknown types.
var DefaultChainable = getNewChainableClass('Chainable');
// Global methods
function getGlobal() {
// Get global context by keyword here to avoid issues with libraries
// that can potentially alter this script's context object.
return testGlobal(typeof global !== 'undefined' && global) ||
testGlobal(typeof window !== 'undefined' && window);
}
function testGlobal(obj) {
// Note that Rhino uses a different "global" keyword so perform an
// extra check here to ensure that it's actually the global object.
return obj && obj.Object === Object ? obj : null;
}
function setupGlobal() {
Sugar = globalContext[SUGAR_GLOBAL];
// istanbul ignore if
if (Sugar) {
// Reuse already defined Sugar global object.
return;
}
Sugar = function(arg) {
forEachProperty(Sugar, function(sugarNamespace, name) {
// Although only the only enumerable properties on the global
// object are Sugar namespaces, environments that can't set
// non-enumerable properties will step through the utility methods
// as well here, so use this check to only allow true namespaces.
if (hasOwn(namespacesByName, name)) {
sugarNamespace.extend(arg);
}
});
return Sugar;
};
// istanbul ignore else
if (typeof module !== 'undefined' && module.exports) {
// Node or webpack environment
module.exports = Sugar;
} else {
// Unwrapped browser environment
try {
globalContext[SUGAR_GLOBAL] = Sugar;
} catch (e) {
// Contexts such as QML have a read-only global context.
}
}
forEachProperty(NATIVE_NAMES.split(' '), function(name) {
createNamespace(name);
});
setGlobalProperties();
}
/***
* @method createNamespace(name)
* @returns SugarNamespace
* @namespace Sugar
* @short Creates a new Sugar namespace.
* @extra This method is for plugin developers who want to define methods to be
* used with natives that Sugar does not handle by default. The new
* namespace will appear on the `Sugar` global with all the methods of
* normal namespaces, including the ability to define new methods. When
* extended, any defined methods will be mapped to `name` in the global
* context.
*
* @example
*
* Sugar.createNamespace('Boolean');
*
* @param {string} name - The namespace name.
*
***/
function createNamespace(name) {
// Is the current namespace Object?
var isObject = name === 'Object';
// A Sugar namespace is also a chainable class: Sugar.Array, etc.
var sugarNamespace = getNewChainableClass(name, true);
/***
* @method extend([opts])
* @returns Sugar
* @namespace Sugar
* @short Extends Sugar defined methods onto natives.
* @extra This method can be called on individual namespaces like
* `Sugar.Array` or on the `Sugar` global itself, in which case
* [opts] will be forwarded to each `extend` call. For more,
* see `extending`.
*
* @options
*
* methods An array of method names to explicitly extend.
*
* except An array of method names or global namespaces (`Array`,
* `String`) to explicitly exclude. Namespaces should be the
* actual global objects, not strings.
*
* namespaces An array of global namespaces (`Array`, `String`) to
* explicitly extend. Namespaces should be the actual
* global objects, not strings.
*
* enhance A shortcut to disallow all "enhance" flags at once
* (flags listed below). For more, see `enhanced methods`.
* Default is `true`.
*
* enhanceString A boolean allowing String enhancements. Default is `true`.
*
* enhanceArray A boolean allowing Array enhancements. Default is `true`.
*
* objectPrototype A boolean allowing Sugar to extend Object.prototype
* with instance methods. This option is off by default
* and should generally not be used except with caution.
* For more, see `object methods`.
*
* @example
*
* Sugar.Array.extend();
* Sugar.extend();
*
* @option {Array<string>} [methods]
* @option {Array<string|NativeConstructor>} [except]
* @option {Array<NativeConstructor>} [namespaces]
* @option {boolean} [enhance]
* @option {boolean} [enhanceString]
* @option {boolean} [enhanceArray]
* @option {boolean} [objectPrototype]
* @param {ExtendOptions} [opts]
*
***
* @method extend([opts])
* @returns SugarNamespace
* @namespace SugarNamespace
* @short Extends Sugar defined methods for a specific namespace onto natives.
* @param {ExtendOptions} [opts]
*
***/
var extend = function (opts) {
var nativeClass = globalContext[name], nativeProto = nativeClass.prototype;
var staticMethods = {}, instanceMethods = {}, methodsByName;
function objectRestricted(name, target) {
return isObject && target === nativeProto &&
(!allowObjectPrototype || name === 'get' || name === 'set');
}
function arrayOptionExists(field, val) {
var arr = opts[field];
if (arr) {
for (var i = 0, el; el = arr[i]; i++) {
if (el === val) {
return true;
}
}
}
return false;
}
function arrayOptionExcludes(field, val) {
return opts[field] && !arrayOptionExists(field, val);
}
function disallowedByFlags(methodName, target, flags) {
// Disallowing methods by flag currently only applies if methods already
// exist to avoid enhancing native methods, as aliases should still be
// extended (i.e. Array#all should still be extended even if Array#every
// is being disallowed by a flag).
if (!target[methodName] || !flags) {
return false;
}
for (var i = 0; i < flags.length; i++) {
if (opts[flags[i]] === false) {
return true;
}
}
}
function namespaceIsExcepted() {
return arrayOptionExists('except', nativeClass) ||
arrayOptionExcludes('namespaces', nativeClass);
}
function methodIsExcepted(methodName) {
return arrayOptionExists('except', methodName);
}
function canExtend(methodName, method, target) {
return !objectRestricted(methodName, target) &&
!disallowedByFlags(methodName, target, method.flags) &&
!methodIsExcepted(methodName);
}
opts = opts || {};
methodsByName = opts.methods;
if (namespaceIsExcepted()) {
return;
} else if (isObject && typeof opts.objectPrototype === 'boolean') {
// Store "objectPrototype" flag for future reference.
allowObjectPrototype = opts.objectPrototype;
}
forEachProperty(methodsByName || sugarNamespace, function(method, methodName) {
if (methodsByName) {
// If we have method names passed in an array,
// then we need to flip the key and value here
// and find the method in the Sugar namespace.
methodName = method;
method = sugarNamespace[methodName];
}
if (hasOwn(method, 'instance') && canExtend(methodName, method, nativeProto)) {
instanceMethods[methodName] = method.instance;
}
if(hasOwn(method, 'static') && canExtend(methodName, method, nativeClass)) {
staticMethods[methodName] = method;
}
});
// Accessing the extend target each time instead of holding a reference as
// it may have been overwritten (for example Date by Sinon). Also need to
// access through the global to allow extension of user-defined namespaces.
extendNative(nativeClass, staticMethods);
extendNative(nativeProto, instanceMethods);
if (!methodsByName) {
// If there are no method names passed, then
// all methods in the namespace will be extended
// to the native. This includes all future defined
// methods, so add a flag here to check later.
setProperty(sugarNamespace, 'active', true);
}
return sugarNamespace;
};
function defineWithOptionCollect(methodName, instance, args) {
setProperty(sugarNamespace, methodName, function(arg1, arg2, arg3) {
var opts = collectDefineOptions(arg1, arg2, arg3);
defineMethods(sugarNamespace, opts.methods, instance, args, opts.last);
return sugarNamespace;
});
}
/***
* @method defineStatic(methods)
* @returns SugarNamespace
* @namespace SugarNamespace
* @short Defines static methods on the namespace that can later be extended
* onto the native globals.
* @extra Accepts either a single object mapping names to functions, or name
* and function as two arguments. If `extend` was previously called
* with no arguments, the method will be immediately mapped to its
* native when defined.
*
* @example
*
* Sugar.Number.defineStatic({
* isOdd: function (num) {
* return num % 2 === 1;
* }
* });
*
* @signature defineStatic(methodName, methodFn)
* @param {Object} methods - Methods to be defined.
* @param {string} methodName - Name of a single method to be defined.
* @param {Function} methodFn - Function body of a single method to be defined.
***/
defineWithOptionCollect('defineStatic', STATIC);
/***
* @method defineInstance(methods)
* @returns SugarNamespace
* @namespace SugarNamespace
* @short Defines methods on the namespace that can later be extended as
* instance methods onto the native prototype.
* @extra Accepts either a single object mapping names to functions, or name
* and function as two arguments. All functions should accept the
* native for which they are mapped as their first argument, and should
* never refer to `this`. If `extend` was previously called with no
* arguments, the method will be immediately mapped to its native when
* defined.
*
* Methods cannot accept more than 4 arguments in addition to the
* native (5 arguments total). Any additional arguments will not be
* mapped. If the method needs to accept unlimited arguments, use
* `defineInstanceWithArguments`. Otherwise if more options are
* required, use an options object instead.
*
* @example
*
* Sugar.Number.defineInstance({
* square: function (num) {
* return num * num;
* }
* });
*
* @signature defineInstance(methodName, methodFn)
* @param {Object} methods - Methods to be defined.
* @param {string} methodName - Name of a single method to be defined.
* @param {Function} methodFn - Function body of a single method to be defined.
***/
defineWithOptionCollect('defineInstance', INSTANCE);
/***
* @method defineInstanceAndStatic(methods)
* @returns SugarNamespace
* @namespace SugarNamespace
* @short A shortcut to define both static and instance methods on the namespace.
* @extra This method is intended for use with `Object` instance methods. Sugar
* will not map any methods to `Object.prototype` by default, so defining
* instance methods as static helps facilitate their proper use.
*
* @example
*
* Sugar.Object.defineInstanceAndStatic({
* isAwesome: function (obj) {
* // check if obj is awesome!
* }
* });
*
* @signature defineInstanceAndStatic(methodName, methodFn)
* @param {Object} methods - Methods to be defined.
* @param {string} methodName - Name of a single method to be defined.
* @param {Function} methodFn - Function body of a single method to be defined.
***/
defineWithOptionCollect('defineInstanceAndStatic', INSTANCE | STATIC);
/***
* @method defineStaticWithArguments(methods)
* @returns SugarNamespace
* @namespace SugarNamespace
* @short Defines static methods that collect arguments.
* @extra This method is identical to `defineStatic`, except that when defined
* methods are called, they will collect any arguments past `n - 1`,
* where `n` is the number of arguments that the method accepts.
* Collected arguments will be passed to the method in an array
* as the last argument defined on the function.
*
* @example
*
* Sugar.Number.defineStaticWithArguments({
* addAll: function (num, args) {
* for (var i = 0; i < args.length; i++) {
* num += args[i];
* }
* return num;
* }
* });
*
* @signature defineStaticWithArguments(methodName, methodFn)
* @param {Object} methods - Methods to be defined.
* @param {string} methodName - Name of a single method to be defined.
* @param {Function} methodFn - Function body of a single method to be defined.
***/
defineWithOptionCollect('defineStaticWithArguments', STATIC, true);
/***
* @method defineInstanceWithArguments(methods)
* @returns SugarNamespace
* @namespace SugarNamespace
* @short Defines instance methods that collect arguments.
* @extra This method is identical to `defineInstance`, except that when
* defined methods are called, they will collect any arguments past
* `n - 1`, where `n` is the number of arguments that the method
* accepts. Collected arguments will be passed to the method as the
* last argument defined on the function.
*
* @example
*
* Sugar.Number.defineInstanceWithArguments({
* addAll: function (num, args) {
* for (var i = 0; i < args.length; i++) {
* num += args[i];
* }
* return num;
* }
* });
*
* @signature defineInstanceWithArguments(methodName, methodFn)
* @param {Object} methods - Methods to be defined.
* @param {string} methodName - Name of a single method to be defined.
* @param {Function} methodFn - Function body of a single method to be defined.
***/
defineWithOptionCollect('defineInstanceWithArguments', INSTANCE, true);
/***
* @method defineStaticPolyfill(methods)
* @returns SugarNamespace
* @namespace SugarNamespace
* @short Defines static methods that are mapped onto the native if they do
* not already exist.
* @extra Intended only for use creating polyfills that follow the ECMAScript
* spec. Accepts either a single object mapping names to functions, or
* name and function as two arguments. Note that polyfill methods will
* be immediately mapped onto their native prototype regardless of the
* use of `extend`.
*
* @example
*
* Sugar.Object.defineStaticPolyfill({
* keys: function (obj) {
* // get keys!
* }
* });
*
* @signature defineStaticPolyfill(methodName, methodFn)
* @param {Object} methods - Methods to be defined.
* @param {string} methodName - Name of a single method to be defined.
* @param {Function} methodFn - Function body of a single method to be defined.
***/
setProperty(sugarNamespace, 'defineStaticPolyfill', function(arg1, arg2, arg3) {
var opts = collectDefineOptions(arg1, arg2, arg3);
extendNative(globalContext[name], opts.methods, true, opts.last);
return sugarNamespace;
});
/***
* @method defineInstancePolyfill(methods)
* @returns SugarNamespace
* @namespace SugarNamespace
* @short Defines instance methods that are mapped onto the native prototype
* if they do not already exist.
* @extra Intended only for use creating polyfills that follow the ECMAScript
* spec. Accepts either a single object mapping names to functions, or
* name and function as two arguments. This method differs from
* `defineInstance` as there is no static signature (as the method
* is mapped as-is to the native), so it should refer to its `this`
* object. Note that polyfill methods will be immediately mapped onto
* their native prototype regardless of the use of `extend`.
*
* @example
*
* Sugar.Array.defineInstancePolyfill({
* indexOf: function (arr, el) {
* // index finding code here!
* }
* });
*
* @signature defineInstancePolyfill(methodName, methodFn)
* @param {Object} methods - Methods to be defined.
* @param {string} methodName - Name of a single method to be defined.
* @param {Function} methodFn - Function body of a single method to be defined.
***/
setProperty(sugarNamespace, 'defineInstancePolyfill', function(arg1, arg2, arg3) {
var opts = collectDefineOptions(arg1, arg2, arg3);
extendNative(globalContext[name].prototype, opts.methods, true, opts.last);
// Map instance polyfills to chainable as well.
forEachProperty(opts.methods, function(fn, methodName) {
defineChainableMethod(sugarNamespace, methodName, fn);
});
return sugarNamespace;
});
/***
* @method alias(toName, from)
* @returns SugarNamespace
* @namespace SugarNamespace
* @short Aliases one Sugar method to another.
*
* @example
*
* Sugar.Array.alias('all', 'every');
*
* @signature alias(toName, fn)
* @param {string} toName - Name for new method.
* @param {string|Function} from - Method to alias, or string shortcut.
***/
setProperty(sugarNamespace, 'alias', function(name, source) {
var method = typeof source === 'string' ? sugarNamespace[source] : source;
setMethod(sugarNamespace, name, method);
return sugarNamespace;
});
// Each namespace can extend only itself through its .extend method.
setProperty(sugarNamespace, 'extend', extend);
// Cache the class to namespace relationship for later use.
namespacesByName[name] = sugarNamespace;
namespacesByClassString['[object ' + name + ']'] = sugarNamespace;
mapNativeToChainable(name);
mapObjectChainablesToNamespace(sugarNamespace);
// Export
return Sugar[name] = sugarNamespace;
}
function setGlobalProperties() {
setProperty(Sugar, 'VERSION', '2.0.6');
setProperty(Sugar, 'extend', Sugar);
setProperty(Sugar, 'toString', toString);
setProperty(Sugar, 'createNamespace', createNamespace);
setProperty(Sugar, 'util', {
'hasOwn': hasOwn,
'getOwn': getOwn,
'setProperty': setProperty,
'classToString': classToString,
'defineProperty': defineProperty,
'forEachProperty': forEachProperty,
'mapNativeToChainable': mapNativeToChainable
});
}
function toString() {
return SUGAR_GLOBAL;
}
// Defining Methods
function defineMethods(sugarNamespace, methods, type, args, flags) {
forEachProperty(methods, function(method, methodName) {
var instanceMethod, staticMethod = method;
if (args) {
staticMethod = wrapMethodWithArguments(method);
}
if (flags) {
staticMethod.flags = flags;
}
// A method may define its own custom implementation, so
// make sure that's not the case before creating one.
if (type & INSTANCE && !method.instance) {
instanceMethod = wrapInstanceMethod(method, args);
setProperty(staticMethod, 'instance', instanceMethod);
}
if (type & STATIC) {
setProperty(staticMethod, 'static', true);
}
setMethod(sugarNamespace, methodName, staticMethod);
if (sugarNamespace.active) {
// If the namespace has been activated (.extend has been called),
// then map this method as well.
sugarNamespace.extend(methodName);
}
});
}
function collectDefineOptions(arg1, arg2, arg3) {
var methods, last;
if (typeof arg1 === 'string') {
methods = {};
methods[arg1] = arg2;
last = arg3;
} else {
methods = arg1;
last = arg2;
}
return {
last: last,
methods: methods
};
}
function wrapInstanceMethod(fn, args) {
return args ? wrapMethodWithArguments(fn, true) : wrapInstanceMethodFixed(fn);
}
function wrapMethodWithArguments(fn, instance) {
// Functions accepting enumerated arguments will always have "args" as the
// last argument, so subtract one from the function length to get the point
// at which to start collecting arguments. If this is an instance method on
// a prototype, then "this" will be pushed into the arguments array so start
// collecting 1 argument earlier.
var startCollect = fn.length - 1 - (instance ? 1 : 0);
return function() {
var args = [], collectedArgs = [], len;
if (instance) {
args.push(this);
}
len = Math.max(arguments.length, startCollect);
// Optimized: no leaking arguments
for (var i = 0; i < len; i++) {
if (i < startCollect) {
args.push(arguments[i]);
} else {
collectedArgs.push(arguments[i]);
}
}
args.push(collectedArgs);
return fn.apply(this, args);
};
}
function wrapInstanceMethodFixed(fn) {
switch(fn.length) {
// Wrapped instance methods will always be passed the instance
// as the first argument, but requiring the argument to be defined
// may cause confusion here, so return the same wrapped function regardless.
case 0:
case 1:
return function() {
return fn(this);
};
case 2:
return function(a) {
return fn(this, a);
};
case 3:
return function(a, b) {
return fn(this, a, b);
};
case 4:
return function(a, b, c) {
return fn(this, a, b, c);
};
case 5:
return function(a, b, c, d) {
return fn(this, a, b, c, d);
};
}
}
// Method helpers
function extendNative(target, source, polyfill, override) {
forEachProperty(source, function(method, name) {
if (polyfill && !override && target[name]) {
// Method exists, so bail.
return;
}
setProperty(target, name, method);
});
}
function setMethod(sugarNamespace, methodName, method) {
sugarNamespace[methodName] = method;
if (method.instance) {
defineChainableMethod(sugarNamespace, methodName, method.instance, true);
}
}
// Chainables
function getNewChainableClass(name) {
var fn = function SugarChainable(obj, arg) {
if (!(this instanceof fn)) {
return new fn(obj, arg);
}
if (this.constructor !== fn) {
// Allow modules to define their own constructors.
obj = this.constructor.apply(obj, arguments);
}
this.raw = obj;
};
setProperty(fn, 'toString', function() {
return SUGAR_GLOBAL + name;
});
setProperty(fn.prototype, 'valueOf', function() {
return this.raw;
});
return fn;
}
function defineChainableMethod(sugarNamespace, methodName, fn) {
var wrapped = wrapWithChainableResult(fn), existing, collision, dcp;
dcp = DefaultChainable.prototype;
existing = dcp[methodName];
// If the method was previously defined on the default chainable, then a
// collision exists, so set the method to a disambiguation function that will
// lazily evaluate the object and find it's associated chainable. An extra
// check is required to avoid false positives from Object inherited methods.
collision = existing && existing !== Object.prototype[methodName];
// The disambiguation function is only required once.
if (!existing || !existing.disambiguate) {
dcp[methodName] = collision ? disambiguateMethod(methodName) : wrapped;
}
// The target chainable always receives the wrapped method. Additionally,
// if the target chainable is Sugar.Object, then map the wrapped method
// to all other namespaces as well if they do not define their own method
// of the same name. This way, a Sugar.Number will have methods like
// isEqual that can be called on any object without having to traverse up
// the prototype chain and perform disambiguation, which costs cycles.
// Note that the "if" block below actually does nothing on init as Object
// goes first and no other namespaces exist yet. However it needs to be
// here as Object instance methods defined later also need to be mapped
// back onto existing namespaces.
sugarNamespace.prototype[methodName] = wrapped;
if (sugarNamespace === Sugar.Object) {
mapObjectChainableToAllNamespaces(methodName, wrapped);
}
}
function mapObjectChainablesToNamespace(sugarNamespace) {
forEachProperty(Sugar.Object && Sugar.Object.prototype, function(val, methodName) {
if (typeof val === 'function') {
setObjectChainableOnNamespace(sugarNamespace, methodName, val);
}
});
}
function mapObjectChainableToAllNamespaces(methodName, fn) {
forEachProperty(namespacesByName, function(sugarNamespace) {
setObjectChainableOnNamespace(sugarNamespace, methodName, fn);
});
}
function setObjectChainableOnNamespace(sugarNamespace, methodName, fn) {
var proto = sugarNamespace.prototype;
if (!hasOwn(proto, methodName)) {
proto[methodName] = fn;
}
}
function wrapWithChainableResult(fn) {
return function() {
return new DefaultChainable(fn.apply(this.raw, arguments));
};
}
function disambiguateMethod(methodName) {
var fn = function() {
var raw = this.raw, sugarNamespace;
if (raw != null) {
// Find the Sugar namespace for this unknown.
sugarNamespace = namespacesByClassString[classToString(raw)];
}
if (!sugarNamespace) {
// If no sugarNamespace can be resolved, then default
// back to Sugar.Object so that undefined and other
// non-supported types can still have basic object
// methods called on them, such as type checks.
sugarNamespace = Sugar.Object;
}
return new sugarNamespace(raw)[methodName].apply(this, arguments);
};
fn.disambiguate = true;
return fn;
}
function mapNativeToChainable(name, methodNames) {
var sugarNamespace = namespacesByName[name],
nativeProto = globalContext[name].prototype;
if (!methodNames && ownPropertyNames) {
methodNames = ownPropertyNames(nativeProto);
}
forEachProperty(methodNames, function(methodName) {
if (nativeMethodProhibited(methodName)) {
// Sugar chainables have their own constructors as well as "valueOf"
// methods, so exclude them here. The __proto__ argument should be trapped
// by the function check below, however simply accessing this property on
// Object.prototype causes QML to segfault, so pre-emptively excluding it.
return;
}
try {
var fn = nativeProto[methodName];
if (typeof fn !== 'function') {
// Bail on anything not a function.
return;
}
} catch (e) {
// Function.prototype has properties that
// will throw errors when accessed.
return;
}
defineChainableMethod(sugarNamespace, methodName, fn);
});
}
function nativeMethodProhibited(methodName) {
return methodName === 'constructor' ||
methodName === 'valueOf' ||
methodName === '__proto__';
}
// Util
// Internal references
var ownPropertyNames = Object.getOwnPropertyNames,
internalToString = Object.prototype.toString,
internalHasOwnProperty = Object.prototype.hasOwnProperty;
// Defining this as a variable here as the ES5 module
// overwrites it to patch DONTENUM.
var forEachProperty = function (obj, fn) {
for(var key in obj) {
if (!hasOwn(obj, key)) continue;
if (fn.call(obj, obj[key], key, obj) === false) break;
}
};
// istanbul ignore next
function definePropertyShim(obj, prop, descriptor) {
obj[prop] = descriptor.value;
}
function setProperty(target, name, value, enumerable) {
defineProperty(target, name, {
value: value,
enumerable: !!enumerable,
configurable: true,
writable: true
});
}
// PERF: Attempts to speed this method up get very Heisenbergy. Quickly
// returning based on typeof works for primitives, but slows down object
// types. Even === checks on null and undefined (no typeof) will end up
// basically breaking even. This seems to be as fast as it can go.
function classToString(obj) {
return internalToString.call(obj);
}
function hasOwn(obj, prop) {
return !!obj && internalHasOwnProperty.call(obj, prop);
}
function getOwn(obj, prop) {
if (hasOwn(obj, prop)) {
return obj[prop];
}
}
setupGlobal();
/***
* @module Common
* @description Internal utility and common methods.
***/
// Flag allowing native methods to be enhanced.
var ENHANCEMENTS_FLAG = 'enhance';
// For type checking, etc. Excludes object as this is more nuanced.
var NATIVE_TYPES = 'Boolean Number String Date RegExp Function Array Error Set Map';
// Do strings have no keys?
var NO_KEYS_IN_STRING_OBJECTS = !('0' in Object('a'));
// Prefix for private properties.
var PRIVATE_PROP_PREFIX = '_sugar_';
// Matches 1..2 style ranges in properties.
var PROPERTY_RANGE_REG = /^(.*?)\[([-\d]*)\.\.([-\d]*)\](.*)$/;
// WhiteSpace/LineTerminator as defined in ES5.1 plus Unicode characters in the Space, Separator category.
var TRIM_CHARS = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
// Regex for matching a formatted string.
var STRING_FORMAT_REG = /([{}])\1|{([^}]*)}|(%)%|(%(\w*))/g;
// Common chars
var HALF_WIDTH_ZERO = 0x30,
FULL_WIDTH_ZERO = 0xff10,
HALF_WIDTH_PERIOD = '.',
FULL_WIDTH_PERIOD = '.',
HALF_WIDTH_COMMA = ',',
OPEN_BRACE = '{',
CLOSE_BRACE = '}';
// Namespace aliases
var sugarObject = Sugar.Object,
sugarArray = Sugar.Array,
sugarDate = Sugar.Date,
sugarString = Sugar.String,
sugarNumber = Sugar.Number,
sugarFunction = Sugar.Function,
sugarRegExp = Sugar.RegExp;
// Class checks
var isSerializable,
isBoolean, isNumber, isString,
isDate, isRegExp, isFunction,
isArray, isSet, isMap, isError;
function buildClassChecks() {
var knownTypes = {};
function addCoreTypes() {
var names = spaceSplit(NATIVE_TYPES);
isBoolean = buildPrimitiveClassCheck(names[0]);
isNumber = buildPrimitiveClassCheck(names[1]);
isString = buildPrimitiveClassCheck(names[2]);
isDate = buildClassCheck(names[3]);
isRegExp = buildClassCheck(names[4]);
// Wanted to enhance performance here by using simply "typeof"
// but Firefox has two major issues that make this impossible,
// one fixed, the other not, so perform a full class check here.
//
// 1. Regexes can be typeof "function" in FF < 3
// https://bugzilla.mozilla.org/show_bug.cgi?id=61911 (fixed)
//
// 2. HTMLEmbedElement and HTMLObjectElement are be typeof "function"
// https://bugzilla.mozilla.org/show_bug.cgi?id=268945 (won't fix)
isFunction = buildClassCheck(names[5]);
// istanbul ignore next
isArray = Array.isArray || buildClassCheck(names[6]);
isError = buildClassCheck(names[7]);
isSet = buildClassCheck(names[8], typeof Set !== 'undefined' && Set);
isMap = buildClassCheck(names[9], typeof Map !== 'undefined' && Map);
// Add core types as known so that they can be checked by value below,
// notably excluding Functions and adding Arguments and Error.
addKnownType('Arguments');
addKnownType(names[0]);
addKnownType(names[1]);
addKnownType(names[2]);
addKnownType(names[3]);
addKnownType(names[4]);
addKnownType(names[6]);
}
function addArrayTypes() {
var types = 'Int8 Uint8 Uint8Clamped Int16 Uint16 Int32 Uint32 Float32 Float64';
forEach(spaceSplit(types), function(str) {
addKnownType(str + 'Array');
});
}
function addKnownType(className) {
var str = '[object '+ className +']';
knownTypes[str] = true;
}
function isKnownType(className) {
return knownTypes[className];
}
function buildClassCheck(className, globalObject) {
// istanbul ignore if
if (globalObject && isClass(new globalObject, 'Object')) {
return getConstructorClassCheck(globalObject);
} else {