forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sugar.dev.js
8212 lines (7397 loc) · 258 KB
/
sugar.dev.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 Library edge
*
* Freely distributable and licensed under the MIT-style license.
* Copyright (c) 2013 Andrew Plummer
* http://sugarjs.com/
*
* ---------------------------- */
(function(){
'use strict';
/***
* @package Core
* @description Core method extension and restoration.
***/
// The global to export.
var Sugar = {};
// An optimization for GCC.
var object = Object;
// The global context
var globalContext = typeof global !== 'undefined' ? global : window;
// Is the environment node?
var hasExports = typeof module !== 'undefined' && module.exports;
// No conflict mode
var noConflict = hasExports && typeof process !== 'undefined' ? process.env['SUGAR_NO_CONFLICT'] : false;
// Internal hasOwnProperty
var internalHasOwnProperty = object.prototype.hasOwnProperty;
// Property descriptors exist in IE8 but will error when trying to define a property on
// native objects. IE8 does not have defineProperies, however, so this check saves a try/catch block.
var propertyDescriptorSupport = !!(object.defineProperty && object.defineProperties);
// Natives by name.
var natives = 'Boolean,Number,String,Array,Date,RegExp,Function'.split(',');
// Proxy objects by class.
var proxies = {};
function initializeGlobal() {
Sugar = {
/***
* @method Sugar.extend(<target>, <methods>, [instance] = true)
* @short This method exposes Sugar's core ability to extend Javascript natives, and is useful for creating custom plugins.
* @extra <target> should be the Javascript native function such as %String%, %Number%, etc. <methods> is an object containing the methods to extend. When [instance] is true the methods will be mapped to <target>'s prototype, if false they will be mapped onto <target> itself. For more see @global.
***/
'extend': extend,
/***
* @method Sugar.restore(<target>, ...)
* @short Restores Sugar methods that may have been overwritten by other scripts.
* @extra <target> should be the Javascript native function such as %String%, %Number%, etc. Arguments after this may be an enumerated list of method names to restore or can be omitted to restore all.
***/
'restore': restore,
/***
* @method Sugar.revert(<target>, ...)
* @short Reverts Sugar methods to what the were before they were added.
* @extra This method can be useful if Sugar methods are causing conflicts with other scripts. <target> should be the Javascript native function such as %String%, %Number%, etc. Arguments after this may be an enumerated list of method names to revert or can be omitted to revert all.
* @short Reverts stuff.
***/
'revert': revert,
'noConflict': noConflict
};
if (hasExports) {
module.exports = Sugar;
} else {
globalContext['Sugar'] = Sugar;
}
}
function initializeNatives() {
iterateOverObject(natives.concat('Object'), function(i, name) {
proxies[globalContext[name]] = name;
Sugar[name] = {};
});
}
// Class extending methods
function extend(klass, methods, instance, polyfill, override) {
var extendee;
instance = instance !== false;
extendee = instance ? klass.prototype : klass;
iterateOverObject(methods, function(name, prop) {
var existing = checkGlobal('method', klass, name, extendee),
original = checkGlobal('original', klass, name, extendee),
existed = name in extendee;
if(typeof polyfill === 'function' && existing) {
prop = wrapExisting(existing, prop, polyfill);
}
defineOnGlobal(klass, name, instance, original, prop, existed);
if(canDefineOnNative(klass, polyfill, existing, override)) {
setProperty(extendee, name, prop);
}
});
}
function alias(klass, target, source) {
var method = getProxy(klass)[source];
var obj = {};
obj[target] = method['method'];
extend(klass, obj, method['instance']);
}
function restore(klass, methods) {
if(noConflict) return;
return batchMethodExecute(klass, methods, function(target, name, m) {
setProperty(target, name, m.method);
});
}
function revert(klass, methods) {
return batchMethodExecute(klass, methods, function(target, name, m) {
if(m['existed']) {
setProperty(target, name, m['original']);
} else {
delete target[name];
}
});
}
function batchMethodExecute(klass, methods, fn) {
var all = !methods, changed = false;
if(typeof methods === 'string') methods = [methods];
iterateOverObject(getProxy(klass), function(name, m) {
if(all || methods.indexOf(name) !== -1) {
changed = true;
fn(m['instance'] ? klass.prototype : klass, name, m);
}
});
return changed;
}
function checkGlobal(type, klass, name, extendee) {
var proxy = getProxy(klass), methodExists;
methodExists = proxy && hasOwnProperty(proxy, name);
if(methodExists) {
return proxy[name][type];
} else {
return extendee[name];
}
}
function canDefineOnNative(klass, polyfill, existing, override) {
if(override) {
return true;
} else if(polyfill === true) {
return !existing;
}
return !noConflict || !proxies[klass];
}
function wrapExisting(originalFn, extendedFn, condition) {
return function(a) {
return condition.apply(this, arguments) ?
extendedFn.apply(this, arguments) :
originalFn.apply(this, arguments);
}
}
function wrapInstanceAsClass(fn) {
return function(obj) {
var args = arguments, newArgs = [], i;
for(i = 1;i < args.length;i++) {
newArgs.push(args[i]);
}
return fn.apply(obj, newArgs);
};
}
function defineOnGlobal(klass, name, instance, original, prop, existed) {
var proxy = getProxy(klass), result;
if(!proxy) return;
result = instance ? wrapInstanceAsClass(prop) : prop;
setProperty(proxy, name, result, true);
if(typeof prop === 'function') {
setProperty(result, 'original', original);
setProperty(result, 'method', prop);
setProperty(result, 'existed', existed);
setProperty(result, 'instance', instance);
}
}
function getProxy(klass) {
return Sugar[proxies[klass]];
}
function setProperty(target, name, property, enumerable) {
if(propertyDescriptorSupport) {
object.defineProperty(target, name, {
'value': property,
'enumerable': !!enumerable,
'configurable': true,
'writable': true
});
} else {
target[name] = property;
}
}
function iterateOverObject(obj, fn) {
var key;
for(key in obj) {
if(!hasOwnProperty(obj, key)) continue;
if(fn.call(obj, key, obj[key], obj) === false) break;
}
}
function hasOwnProperty(obj, prop) {
return !!obj && internalHasOwnProperty.call(obj, prop);
}
initializeGlobal();
initializeNatives();
/***
* @package Common
* @description Internal utility and common methods.
***/
// A few optimizations for Google Closure Compiler will save us a couple kb in the release script.
var object = Object, array = Array, regexp = RegExp, date = Date, string = String, number = Number, func = Function, math = Math, Undefined;
var sugarObject = Sugar.Object, sugarArray = Sugar.Array, sugarDate = Sugar.Date, sugarString = Sugar.String, sugarNumber = Sugar.Number;
// Internal toString
var internalToString = object.prototype.toString;
// Are regexes type function?
var regexIsFunction = typeof regexp() === 'function';
// Do strings have no keys?
var noKeysInStringObjects = !('0' in new string('a'));
// Type check methods need a way to be accessed dynamically.
var typeChecks = {};
// Classes that can be matched by value
var matchedByValueReg = /^\[object Date|Array|String|Number|RegExp|Boolean|Arguments\]$/;
var isBoolean = buildPrimitiveClassCheck('boolean', natives[0]);
var isNumber = buildPrimitiveClassCheck('number', natives[1]);
var isString = buildPrimitiveClassCheck('string', natives[2]);
var isArray = buildClassCheck(natives[3]);
var isDate = buildClassCheck(natives[4]);
var isRegExp = buildClassCheck(natives[5]);
// Wanted to enhance performance here by using simply "typeof"
// but Firefox has two major issues that make this impossible,
// one fixed, the other not. Despite being typeof "function"
// the objects below still report in as [object Function], so
// we need to 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)
//
var isFunction = buildClassCheck(natives[6]);
function isClass(obj, klass, cached) {
var k = cached || className(obj);
return k === '[object '+klass+']';
}
function buildClassCheck(klass) {
var fn = (klass === 'Array' && array.isArray) || function(obj, cached) {
return isClass(obj, klass, cached);
};
typeChecks[klass] = fn;
return fn;
}
function buildPrimitiveClassCheck(type, klass) {
var fn = function(obj) {
if(isObjectType(obj)) {
return isClass(obj, klass);
}
return typeof obj === type;
}
typeChecks[klass] = fn;
return fn;
}
function className(obj) {
return internalToString.call(obj);
}
function extendSimilar(klass, set, fn, instance, polyfill, override) {
var methods = {};
set = isString(set) ? set.split(',') : set;
set.forEach(function(name, i) {
fn(methods, name, i);
});
extend(klass, methods, instance, polyfill, override);
}
// Argument helpers
function isArgumentsObject(obj) {
// .callee exists on Arguments objects in < IE8
return hasProperty(obj, 'length') && (className(obj) === '[object Arguments]' || !!obj.callee);
}
function multiArgs(args, fn, from) {
var result = [], i = from || 0, len;
for(len = args.length; i < len; i++) {
result.push(args[i]);
if(fn) fn.call(args, args[i], i);
}
return result;
}
function flattenedArgs(args, fn, from) {
var arg = args[from || 0];
if(isArray(arg)) {
args = arg;
from = 0;
}
return multiArgs(args, fn, from);
}
function checkCallback(fn) {
if(!fn || !fn.call) {
throw new TypeError('Callback is not callable');
}
}
// General helpers
function isDefined(o) {
return o !== Undefined;
}
function isUndefined(o) {
return o === Undefined;
}
// Object helpers
function hasProperty(obj, prop) {
return !isPrimitiveType(obj) && prop in obj;
}
function isObjectType(obj) {
// 1. Check for null
// 2. Check for regexes in environments where they are "functions".
return !!obj && (typeof obj === 'object' || (regexIsFunction && isRegExp(obj)));
}
function isPrimitiveType(obj) {
var type = typeof obj;
return obj == null || type === 'string' || type === 'number' || type === 'boolean';
}
function isPlainObject(obj, klass) {
klass = klass || className(obj);
try {
// Not own constructor property must be Object
// This code was borrowed from jQuery.isPlainObject
if (obj && obj.constructor &&
!hasOwnProperty(obj, 'constructor') &&
!hasOwnProperty(obj.constructor.prototype, 'isPrototypeOf')) {
return false;
}
} catch (e) {
// IE8,9 Will throw exceptions on certain host objects.
return false;
}
// === on the constructor is not safe across iframes
// 'hasOwnProperty' ensures that the object also inherits
// from Object, which is false for DOMElements in IE.
return !!obj && klass === '[object Object]' && 'hasOwnProperty' in obj;
}
function simpleRepeat(n, fn) {
for(var i = 0; i < n; i++) {
fn(i);
}
}
function simpleMerge(target, source) {
iterateOverObject(source, function(key) {
target[key] = source[key];
});
return target;
}
// Make primtives types like strings into objects.
function coercePrimitiveToObject(obj) {
if(isPrimitiveType(obj)) {
obj = object(obj);
}
if(noKeysInStringObjects && isString(obj)) {
forceStringCoercion(obj);
}
return obj;
}
// Force strings to have their indexes set in
// environments that don't do this automatically.
function forceStringCoercion(obj) {
var i = 0, chr;
while(chr = obj.charAt(i)) {
obj[i++] = chr;
}
}
// Hash definition
function Hash(obj) {
simpleMerge(this, coercePrimitiveToObject(obj));
};
Hash.prototype.constructor = object;
// Math helpers
var abs = math.abs;
var pow = math.pow;
var ceil = math.ceil;
var floor = math.floor;
var round = math.round;
var min = math.min;
var max = math.max;
function withPrecision(val, precision, fn) {
var multiplier = pow(10, abs(precision || 0));
fn = fn || round;
if(precision < 0) multiplier = 1 / multiplier;
return fn(val * multiplier) / multiplier;
}
// Full width number helpers
var HalfWidthZeroCode = 0x30;
var HalfWidthNineCode = 0x39;
var FullWidthZeroCode = 0xff10;
var FullWidthNineCode = 0xff19;
var HalfWidthPeriod = '.';
var FullWidthPeriod = '.';
var HalfWidthComma = ',';
// Used here and later in the Date package.
var FullWidthDigits = '';
var NumberNormalizeMap = {};
var NumberNormalizeReg;
function codeIsNumeral(code) {
return (code >= HalfWidthZeroCode && code <= HalfWidthNineCode) ||
(code >= FullWidthZeroCode && code <= FullWidthNineCode);
}
function buildNumberHelpers() {
var digit, i;
for(i = 0; i <= 9; i++) {
digit = chr(i + FullWidthZeroCode);
FullWidthDigits += digit;
NumberNormalizeMap[digit] = chr(i + HalfWidthZeroCode);
}
NumberNormalizeMap[HalfWidthComma] = '';
NumberNormalizeMap[FullWidthPeriod] = HalfWidthPeriod;
// Mapping this to itself to easily be able to easily
// capture it in stringToNumber to detect decimals later.
NumberNormalizeMap[HalfWidthPeriod] = HalfWidthPeriod;
NumberNormalizeReg = regexp('[' + FullWidthDigits + FullWidthPeriod + HalfWidthComma + HalfWidthPeriod + ']', 'g');
}
// String helpers
function chr(num) {
return string.fromCharCode(num);
}
// WhiteSpace/LineTerminator as defined in ES5.1 plus Unicode characters in the Space, Separator category.
function getTrimmableCharacters() {
return '\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';
}
function repeatString(str, num) {
var result = '';
str = str.toString();
while (num > 0) {
if (num & 1) {
result += str;
}
if (num >>= 1) {
str += str;
}
}
return result;
}
// Returns taking into account full-width characters, commas, and decimals.
function stringToNumber(str, base) {
var sanitized, isDecimal;
sanitized = str.replace(NumberNormalizeReg, function(chr) {
var replacement = NumberNormalizeMap[chr];
if(replacement === HalfWidthPeriod) {
isDecimal = true;
}
return replacement;
});
return isDecimal ? parseFloat(sanitized) : parseInt(sanitized, base || 10);
}
// Used by Number and Date
function padNumber(num, place, sign, base) {
var str = abs(num).toString(base || 10);
str = repeatString('0', place - str.replace(/\.\d+/, '').length) + str;
if(sign || num < 0) {
str = (num < 0 ? '-' : '+') + str;
}
return str;
}
function getOrdinalizedSuffix(num) {
if(num >= 11 && num <= 13) {
return 'th';
} else {
switch(num % 10) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
default: return 'th';
}
}
}
// RegExp helpers
function getRegExpFlags(reg, add) {
var flags = '';
add = add || '';
function checkFlag(prop, flag) {
if(prop || add.indexOf(flag) > -1) {
flags += flag;
}
}
checkFlag(reg.multiline, 'm');
checkFlag(reg.ignoreCase, 'i');
checkFlag(reg.global, 'g');
checkFlag(reg.sticky, 'y');
return flags;
}
function escapeRegExp(str) {
if(!isString(str)) str = string(str);
return str.replace(/([\\\/\'*+?|()\[\]{}.^$-])/g,'\\$1');
}
// Date helpers
function callDateGet(d, method) {
return d['get' + (d._utc ? 'UTC' : '') + method]();
}
function callDateSet(d, method, value) {
return d['set' + (d._utc ? 'UTC' : '') + method](value);
}
// Used by Array#unique and Object.equal
function stringify(thing, stack) {
var type = typeof thing,
thingIsObject,
thingIsArray,
klass, value,
arr, key, i, len;
// Return quickly if string to save cycles
if(type === 'string') return thing;
klass = internalToString.call(thing);
thingIsObject = isPlainObject(thing, klass);
thingIsArray = isArray(thing, klass);
if(thing != null && thingIsObject || thingIsArray) {
// This method for checking for cyclic structures was egregiously stolen from
// the ingenious method by @kitcambridge from the Underscore script:
// https://github.com/documentcloud/underscore/issues/240
if(!stack) stack = [];
// Allowing a step into the structure before triggering this
// script to save cycles on standard JSON structures and also to
// try as hard as possible to catch basic properties that may have
// been modified.
if(stack.length > 1) {
i = stack.length;
while (i--) {
if (stack[i] === thing) {
return 'CYC';
}
}
}
stack.push(thing);
value = thing.valueOf() + string(thing.constructor);
arr = thingIsArray ? thing : object.keys(thing).sort();
for(i = 0, len = arr.length; i < len; i++) {
key = thingIsArray ? i : arr[i];
value += key + stringify(thing[key], stack);
}
stack.pop();
} else if(1 / thing === -Infinity) {
value = '-0';
} else {
value = string(thing && thing.valueOf ? thing.valueOf() : thing);
}
return type + klass + value;
}
function isEqual(a, b) {
if(a === b) {
// Return quickly up front when matching by reference,
// but be careful about 0 !== -0.
return a !== 0 || 1 / a === 1 / b;
} else if(objectIsMatchedByValue(a) && objectIsMatchedByValue(b)) {
return stringify(a) === stringify(b);
}
return false;
}
function objectIsMatchedByValue(obj) {
// Only known objects are matched by value. This is notably excluding functions, DOM Elements, and instances of
// user-created classes. The latter can arguably be matched by value, but distinguishing between these and
// host objects -- which should never be compared by value -- is very tricky so not dealing with it here.
var klass = className(obj);
return matchedByValueReg.test(klass) || isPlainObject(obj, klass);
}
// Used by Array#at and String#at
function getEntriesForIndexes(obj, args, isString) {
var result,
length = obj.length,
argsLen = args.length,
overshoot = args[argsLen - 1] !== false,
multiple = argsLen > (overshoot ? 1 : 2);
if(!multiple) {
return entryAtIndex(obj, length, args[0], overshoot, isString);
}
result = [];
multiArgs(args, function(index) {
if(isBoolean(index)) return false;
result.push(entryAtIndex(obj, length, index, overshoot, isString));
});
return result;
}
function entryAtIndex(obj, length, index, overshoot, isString) {
if(overshoot) {
index = index % length;
if(index < 0) index = length + index;
}
return isString ? obj.charAt(index) : obj[index];
}
// Used by the Array and Object packages.
function transformArgument(el, map, context, mapArgs) {
if(!map) {
return el;
} else if(map.apply) {
return map.apply(context, mapArgs || []);
} else if(isFunction(el[map])) {
return el[map].call(el);
} else {
return el[map];
}
}
function keysWithObjectCoercion(obj) {
return object.keys(coercePrimitiveToObject(obj));
}
// Object class methods implemented as instance methods. This method
// is being called only on Hash and Object itself, so we don't want
// to go through extend() here as it will create proxies that already
// exist, which we want to avoid.
function buildObjectInstanceMethods(set, target) {
set.forEach(function(name) {
var classFn = sugarObject[name === 'equals' ? 'equal' : name];
var fn = function() {
var args = arguments, newArgs = [this], i;
for(i = 0;i < args.length;i++) {
newArgs.push(args[i]);
}
return classFn.apply(null, newArgs);
}
setProperty(target.prototype, name, fn);
});
}
buildNumberHelpers();
/***
* @package ES5
* @description Shim methods that provide ES5 compatible functionality. This package can be excluded if you do not require legacy browser support (IE8 and below).
*
***/
/***
* Object module
*
***/
extend(object, {
'keys': function(obj) {
var keys = [];
if(!isObjectType(obj) && !isRegExp(obj) && !isFunction(obj)) {
throw new TypeError('Object required');
}
iterateOverObject(obj, function(key, value) {
keys.push(key);
});
return keys;
}
}, false, true);
/***
* Array module
*
***/
// ECMA5 methods
function arrayIndexOf(arr, search, fromIndex, increment) {
var length = arr.length,
fromRight = increment == -1,
start = fromRight ? length - 1 : 0,
index = toIntegerWithDefault(fromIndex, start);
if(index < 0) {
index = length + index;
}
if((!fromRight && index < 0) || (fromRight && index >= length)) {
index = start;
}
while((fromRight && index >= 0) || (!fromRight && index < length)) {
if(arr[index] === search) {
return index;
}
index += increment;
}
return -1;
}
function arrayReduce(arr, fn, initialValue, fromRight) {
var length = arr.length, count = 0, defined = isDefined(initialValue), result, index;
checkCallback(fn);
if(length == 0 && !defined) {
throw new TypeError('Reduce called on empty array with no initial value');
} else if(defined) {
result = initialValue;
} else {
result = arr[fromRight ? length - 1 : count];
count++;
}
while(count < length) {
index = fromRight ? length - count - 1 : count;
if(index in arr) {
result = fn(result, arr[index], index, arr);
}
count++;
}
return result;
}
function toIntegerWithDefault(i, d) {
if(isNaN(i)) {
return d;
} else {
return parseInt(i >> 0);
}
}
function checkFirstArgumentExists(args) {
if(args.length === 0) {
throw new TypeError('First argument must be defined');
}
}
extend(array, {
/***
*
* @method Array.isArray(<obj>)
* @returns Boolean
* @short Returns true if <obj> is an Array.
* @extra This method is provided for browsers that don't support it internally.
* @example
*
* Array.isArray(3) -> false
* Array.isArray(true) -> false
* Array.isArray('wasabi') -> false
* Array.isArray([1,2,3]) -> true
*
***/
'isArray': function(obj) {
return isArray(obj);
}
}, false, true);
extend(array, {
/***
* @method every(<f>, [scope])
* @returns Boolean
* @short Returns true if all elements in the array match <f>.
* @extra [scope] is the %this% object. %all% is provided an alias. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ ['a','a','a'].every(function(n) {
* return n == 'a';
* });
* ['a','a','a'].every('a') -> true
* [{a:2},{a:2}].every({a:2}) -> true
***/
'every': function(fn, scope) {
var length = this.length, index = 0;
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && !fn.call(scope, this[index], index, this)) {
return false;
}
index++;
}
return true;
},
/***
* @method some(<f>, [scope])
* @returns Boolean
* @short Returns true if any element in the array matches <f>.
* @extra [scope] is the %this% object. %any% is provided as an alias. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ ['a','b','c'].some(function(n) {
* return n == 'a';
* });
+ ['a','b','c'].some(function(n) {
* return n == 'd';
* });
* ['a','b','c'].some('a') -> true
* [{a:2},{b:5}].some({a:2}) -> true
***/
'some': function(fn, scope) {
var length = this.length, index = 0;
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && fn.call(scope, this[index], index, this)) {
return true;
}
index++;
}
return false;
},
/***
* @method map(<map>, [scope])
* @returns Array
* @short Maps the array to another array containing the values that are the result of calling <map> on each element.
* @extra [scope] is the %this% object. When <map> is a function, it receives three arguments: the current element, the current index, and a reference to the array. In addition to providing this method for browsers that don't support it natively, this enhanced method also directly accepts a string, which is a shortcut for a function that gets that property (or invokes a function) on each element.
* @example
*
* [1,2,3].map(function(n) {
* return n * 3;
* }); -> [3,6,9]
* ['one','two','three'].map(function(n) {
* return n.length;
* }); -> [3,3,5]
* ['one','two','three'].map('length') -> [3,3,5]
*
***/
'map': function(fn, scope) {
var scope = arguments[1], length = this.length, index = 0, result = new Array(length);
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this) {
result[index] = fn.call(scope, this[index], index, this);
}
index++;
}
return result;
},
/***
* @method filter(<f>, [scope])
* @returns Array
* @short Returns any elements in the array that match <f>.
* @extra [scope] is the %this% object. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ [1,2,3].filter(function(n) {
* return n > 1;
* });
* [1,2,2,4].filter(2) -> 2
*
***/
'filter': function(fn) {
var scope = arguments[1];
var length = this.length, index = 0, result = [];
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && fn.call(scope, this[index], index, this)) {
result.push(this[index]);
}
index++;
}
return result;
},
/***
* @method indexOf(<search>, [fromIndex])
* @returns Number
* @short Searches the array and returns the first index where <search> occurs, or -1 if the element is not found.
* @extra [fromIndex] is the index from which to begin the search. This method performs a simple strict equality comparison on <search>. It does not support enhanced functionality such as searching the contents against a regex, callback, or deep comparison of objects. For such functionality, use the %findIndex% method instead.
* @example
*
* [1,2,3].indexOf(3) -> 1
* [1,2,3].indexOf(7) -> -1
*
***/
'indexOf': function(search) {
var fromIndex = arguments[1];
if(isString(this)) return this.indexOf(search, fromIndex);
return arrayIndexOf(this, search, fromIndex, 1);
},
/***
* @method lastIndexOf(<search>, [fromIndex])
* @returns Number
* @short Searches the array and returns the last index where <search> occurs, or -1 if the element is not found.
* @extra [fromIndex] is the index from which to begin the search. This method performs a simple strict equality comparison on <search>.
* @example
*
* [1,2,1].lastIndexOf(1) -> 2
* [1,2,1].lastIndexOf(7) -> -1
*
***/
'lastIndexOf': function(search) {
var fromIndex = arguments[1];
if(isString(this)) return this.lastIndexOf(search, fromIndex);
return arrayIndexOf(this, search, fromIndex, -1);
},
/***
* @method forEach([fn], [scope])
* @returns Nothing
* @short Iterates over the array, calling [fn] on each loop.
* @extra This method is only provided for those browsers that do not support it natively. [scope] becomes the %this% object.
* @example
*
* ['a','b','c'].forEach(function(a) {
* // Called 3 times: 'a','b','c'
* });
*
***/
'forEach': function(fn) {
var length = this.length, index = 0, scope = arguments[1];
checkCallback(fn);
while(index < length) {
if(index in this) {
fn.call(scope, this[index], index, this);
}
index++;