/
sugar.js
5828 lines (5401 loc) · 184 KB
/
sugar.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
(function() {
// defineProperty exists 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 definePropertySupport = Object.defineProperty && Object.defineProperties;
function extend(klass, instance, override, methods) {
var extendee = instance ? klass.prototype : klass;
storeMethods(klass, instance, methods);
iterateOverObject(methods, function(name, method) {
if(typeof override === 'function') {
defineProperty(extendee, name, wrapNative(extendee[name], method, override));
} else if(override === true || !extendee[name]) {
defineProperty(extendee, name, method);
}
klass.SugarMethods[name] = { instance: instance, method: method };
});
}
function storeMethods(klass, instance, methods) {
if(klass.SugarMethods) return;
klass.SugarMethods = {};
defineProperty(klass, 'sugar', function() {
var args = arguments, all = args.length === 0, done = false;
if(klass === Object && all) {
activateObjectPrototypeMethods();
}
iterateOverObject(klass.SugarMethods, function(name, m) {
if(all || arrayFind(args, name)) {
defineProperty(m.instance ? klass.prototype : klass, name, m.method);
done = true;
}
});
return done;
});
}
function wrapNative(nativeFn, extendedFn, condition) {
return function() {
if(nativeFn && (condition === true || condition.apply(this, arguments))) {
return nativeFn.apply(this, arguments);
} else {
return extendedFn.apply(this, arguments);
}
}
}
function defineProperty(target, name, method) {
if(definePropertySupport) {
Object.defineProperty(target, name, { value: method, configurable: true, enumerable: false, writable: true });
} else {
target[name] = method;
}
}
function iterateOverObject(obj, fn) {
var count = 0;
for(var key in obj) {
if(!obj.hasOwnProperty(key)) continue;
fn.call(obj, key, obj[key], count);
count++;
}
}
function deepEqual(a,b) {
if(typeof a == 'object' && typeof b == 'object' && a !== null && b !== null) {
for(var key in a) {
if(!a.hasOwnProperty(key)) continue;
if(!b.hasOwnProperty(key) || !deepEqual(a[key], b[key])) {
return false;
}
}
return Object.keys(a).length === Object.keys(b).length;
} else {
return a === b;
}
}
function multiMatch(el, match, scope, params) {
if(el === match) {
// Return if exact match
return true;
} else if(Object.isRegExp(match)) {
// Match against a regexp
return match.test(el);
} else if(Object.isFunction(match)) {
// Match against a filtering function
return match.apply(scope, [el].concat(params));
} else if(typeof match === 'object') {
// Match against a hash or array.
return deepEqual(match, el);
} else {
// Otherwise false
return false;
}
}
function transformArgument(args, el, scope, params) {
var transform = args[0];
if(args.length === 0) {
return el;
} else if(!Object.isFunction(transform) && !Object.isString(transform)) {
throw new TypeError('First argument must be a function or a string');
}
if(Object.isFunction(transform)) {
return transform.apply(scope, [el].concat(params));
} else if(typeof el[transform] == 'function') {
return el[transform].call(el);
} else {
return el[transform];
}
}
function multiArgs(args, fn) {
arrayEach(arrayFlatten(Array.prototype.slice.call(args)), fn);
}
// Used for both arrays and strings
function entryAtIndex(arr, args, str) {
var result = [], length = arr.length, loop = args[args.length - 1] !== false, r;
multiArgs(args, function(index) {
if(typeof index === 'boolean') return false;
if(loop) {
index = index % length;
if(index < 0) index = length + index;
}
r = str ? arr.charAt(index) || '' : arr[index];
result.push(r);
});
return result.length < 2 ? result[0] : result;
}
/***
* Object module
*
* Much thanks to "kangax" for his informative aricle about how problems with instanceof and constructor
* http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
*
***/
function instance(obj, str) {
return Object.prototype.toString.call(obj) === '[object '+str+']';
}
function cloneObject(obj, deep, extend) {
var result;
if(Array.isArray(obj)) {
result = [];
} else if(extend) {
result = Object.extended();
} else {
result = {};
}
iterateOverObject(obj, function(k,v) {
if(deep && (Object.isObject(v) || Array.isArray(v))) {
result[k] = cloneObject(v, deep, extend);
} else {
result[k] = v;
}
});
return result;
}
function setParamsObject(obj, param, value, deep) {
var reg = /^(.+?)(\[.*\])$/, isArray, match, allKeys, key;
if(deep !== false && (match = param.match(reg))) {
key = match[1];
allKeys = match[2].replace(/^\[|\]$/g, '').split('][');
arrayEach(allKeys, function(k) {
isArray = !k || k.match(/^\d+$/);
if(!key && Object.isArray(obj)) key = obj.length;
if(!obj[key]) {
obj[key] = isArray ? [] : {};
}
obj = obj[key];
key = k;
});
if(!key && isArray) key = obj.length.toString();
setParamsObject(obj, key, value);
} else if(value.match(/^\d+$/)) {
obj[param] = parseInt(value);
} else if(value === 'true') {
obj[param] = true;
} else if(value === 'false') {
obj[param] = false;
} else {
obj[param] = value;
}
}
function Hash(obj) {
var self = this;
iterateOverObject(obj, function(key, value) {
self[key] = value;
});
}
Hash.prototype.constructor = Object;
extend(Hash, true, false, {
'clone': function(deep) {
return cloneObject(this, deep, true);
}
});
var typeMethods = ['Array','Boolean','Date','Function','Number','String','RegExp'];
var hashMethods = ['keys','values','each','merge','isEmpty','equals','watch'];
/***
* @method Object.sugar(<method1>, <method2>, ...)
* @returns Boolean
* @short Allows extra control and added functionality of Sugar methods.
* @extra The %sugar% method exists on all classes and serves two purposes. 1) It restores control of methods that has been lost. This is particularly useful when using Sugar alongside another library such as Prototype. As Sugar will always defer in the case of a conflict, this method can be used to opt-in functionality per-method or per-class. If no arguments are passed, methods will be restored for the entire class. 2) Calling this method on the %Object% class with no arguments will additionally map extended Object methods (ie. those available on objects created with %Object.extended%) onto Object.prototype, making them available to *all* Javascript objects. This second usage can have unintended consequences so exercise caution here!
*
***
* @method Object.is[Type](<obj>)
* @returns Boolean
* @short Returns true if <obj> is an object of that type.
* @extra %isObject% will return false on anything that is not an object literal, including instances of inherited classes.
* @example
*
* Object.isArray([1,2,3]) -> true
* Object.isDate(3) -> false
* Object.isRegExp(/wasabi/) -> true
* Object.isObject({ broken:'wear' }) -> true
*
***
* @method Object.isArray()
* @set isType
***
* @method Object.isBoolean()
* @set isType
***
* @method Object.isDate()
* @set isType
***
* @method Object.isFunction()
* @set isType
***
* @method Object.isNumber()
* @set isType
***
* @method Object.isString()
* @set isType
***
* @method Object.isRegExp()
* @set isType
***
* @method Object.isObject()
* @set isType
***/
function buildTypeMethods() {
var methods = {};
typeMethods.slice(1).forEach(function(m) {
methods['is' + m] = function(obj) {
return instance(obj, m);
}
});
extend(Object, false, false, methods);
}
function buildHashMethods() {
hashMethods.forEach(function(m) {
defineProperty(Hash.prototype, m, function() {
return Object[m].apply(null, [this].concat(Array.prototype.slice.call(arguments)));
});
});
}
function buildWatch() {
extend(Object, false, true, {
/***
* @method Object.watch(<obj>, <prop>, <fn>)
* @returns Nothing
* @short Watches a property of <obj> and runs <fn> when it changes.
* @extra <fn> is passed three arguments: the property (<prop>), the old value, and the new value. The return value of [fn] will be set as the new value. This method is useful for things such as validating or cleaning the value when it is set. Warning: this method WILL NOT work in browsers that don't support Object.defineProperty. This notably includes IE 8 and below and Opera. This is the only method in Sugar that is not fully compatible with all browsers. The instance method alias is only available on extended objects created with %Object.extended%.
* @example
*
* Object.watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) {
* // Will be run when the property 'foo' is set on the object.
* });
* Object.extended().watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) {
* // Will be run when the property 'foo' is set on the object.
* });
*
***
* @method watch()
* @alias Object.watch
***/
'watch': function(obj, prop, fn) {
if(!definePropertySupport) return;
var value = obj[prop];
Object.defineProperty(obj, prop, {
get: function() {
return value;
},
set: function(to) {
value = fn.call(obj, prop, value, to);
},
enumerable: true,
configurable: true
});
}
});
}
function buildObject() {
extend(Object, false, false, { isArray: Array.isArray });
buildTypeMethods();
buildHashMethods();
buildWatch();
}
function activateObjectPrototypeMethods() {
typeMethods.each(function(m) {
defineProperty(Object.prototype, 'is'+m, function() {
return Object['is'+m](this);
});
});
hashMethods.each(function(m) {
defineProperty(Object.prototype, m, Hash.prototype[m]);
});
defineProperty(Object.prototype, 'clone', function(deep) {
return cloneObject(this, deep, true);
});
}
extend(Object, false, false, {
/***
* @method Object.extended(<obj> = {})
* @returns Extended object
* @short Creates a new object with extended hash-like methods.
* @extra This is equivalent to the standard Object constructor %new Object()% but additionally returns an object with extended hash methods.
* @example
*
* Object.extended()
* Object.extended({ happy:true, pappy:false })
* Object.extended({ happy:true, pappy:false }).keys() -> ['happy','pappy']
*
***/
'extended': function(obj) {
return new Hash(obj);
},
'isObject': function(o) {
if(o === null || o === undefined) {
return false;
} else {
return instance(o, 'Object') && o.constructor === Object;
}
},
/***
* @method Object.each(<obj>, [fn])
* @returns Object
* @short Iterates over each property in <obj> calling [fn] on each iteration.
* @extra The instance method alias is only available on extended objects created with %Object.extended%.
* @example
*
* Object.each({ broken:'wear' }, function(key, value) {
* // Iterates over each key/value pair.
* });
* Object.extended({ broken:'wear' }).each(function(key, value) {
* // Iterates over each key/value pair.
* });
*
***
* @method each()
* @alias Object.each
***/
'each': function(obj, fn) {
if(fn) {
iterateOverObject(obj, function(k,v) {
fn.call(obj, k, v, obj);
});
}
return obj;
},
/***
* @method Object.merge(<obj1>, <obj2>, ...)
* @returns Merged object
* @short Accepts an arbitrary number of objects as arguments and merges them all into <obj1>.
* @extra All arguments must be actual objects. The instance method alias is only available on extended objects created with %Object.extended%.
* @example
*
* Object.merge({a:1},{b:2}) -> { a:1, b:2 }
* Object.extended({a:1}).merge({b:2}) -> { a:1, b:2 }
*
***
* @method merge()
* @alias Object.merge
***/
'merge': function() {
var target = arguments[0];
multiArgs(arguments, function(a) {
if(typeof a !== 'object') return;
iterateOverObject(a, function(key, value) {
target[key] = value;
});
});
return target;
},
/***
* @method Object.isEmpty(<obj>)
* @returns Boolean
* @short Returns true if <obj> is empty.
* @extra The instance method alias is only available on extended objects created with %Object.extended%.
* @example
*
* Object.isEmpty({}) -> true
* Object.isEmpty({foo:'bar'}) -> false
* Object.extended({foo:'bar'}).isEmpty() -> false
*
***
* @method isEmpty()
* @alias Object.isEmpty
***/
'isEmpty': function(obj) {
if(!obj) return true;
return deepEqual(obj, {});
},
/***
* @method Object.equals(<a>, <b>)
* @returns Boolean
* @short Returns true if <a> and <b> are equal.
* @extra The instance method alias is only available on extended objects created with %Object.extended%.
* @example
*
* Object.equals({a:2}, {a:2}) -> true
* Object.equals({a:2}, {a:3}) -> false
* Object.extended({a:2}).equals({a:3}) -> false
*
***
* @method equals()
* @alias Object.equals
***/
'equals': function(a, b) {
return deepEqual(a, b);
},
/***
* @method Object.values(<obj>, [fn])
* @returns Array
* @short Returns an array containing the values in <obj>. Optionally calls [fn] for each value.
* @extra Returned values are in no particular order. The instance method alias is only available on extended objects created with %Object.extended%.
* @example
*
* Object.values({ broken: 'wear' }) -> ['wear']
* Object.values({ broken: 'wear' }, function(value) {
* // Called once for each value.
* });
* Object.extended({ broken: 'wear' }).values() -> ['wear']
*
***
* @method values()
* @alias Object.values
***/
'values': function(obj, fn) {
var values = [];
iterateOverObject(obj, function(k,v) {
values.push(v);
if(fn) fn.call(obj,v);
});
return values;
},
/***
* @method Object.clone(<obj> = {}, [deep] = false)
* @returns Cloned object
* @short Creates a clone (copy) of <obj>.
* @extra Default is a shallow clone, unless [deep] is true. The instance method alias is only available on extended objects created with %Object.extended%.
* @example
*
* Object.clone({foo:'bar'}) -> { foo: 'bar' }
* Object.clone() -> {}
* Object.extended({foo:'bar'}).clone() -> { foo: 'bar' }
*
***
* @method clone()
* @alias Object.clone
***/
'clone': cloneObject,
/***
* @method Object.fromQueryString(<str>, [deep] = true)
* @returns Object
* @short Converts the query string of a URL into an object.
* @extra If [deep] is %false%, conversion will only accept shallow params (ie. no object or arrays with %[]% syntax) as these are not universally supported.
* @example
*
* Object.fromQueryString('foo=bar&broken=wear') -> { foo: 'bar', broken: 'wear' }
* Object.fromQueryString('foo[]=1&foo[]=2') -> { foo: [1,2] }
*
***/
'fromQueryString': function(str, deep) {
var result = Object.extended(), split;
str = str && str.toString ? str.toString() : '';
str.replace(/^.*?\?/, '').unescapeURL().split('&').each(function(p) {
var split = p.split('=');
if(split.length !== 2) return;
setParamsObject(result, split[0], split[1], deep);
});
return result;
}
});
extend(Object, false, function() { return arguments.length < 2; }, {
/***
* @method Object.keys(<obj>, [fn])
* @returns Array
* @short Returns an array containing the keys in <obj>. Optionally calls [fn] for each key.
* @extra Note that this method provides added functionality over the browser native %keys% method, which will not accept [fn]. Returned keys are in no particular order. The instance method alias is only available on extended objects created with %Object.extended%.
* @example
*
* Object.keys({ broken: 'wear' }) -> ['broken']
* Object.keys({ broken: 'wear' }, function(key, value) {
* // Called once for each key.
* });
* Object.extended({ broken: 'wear' }).keys() -> ['broken']
*
***
* @method keys()
* @alias Object.keys
***/
'keys': function(obj, fn) {
var t = typeof obj;
if(obj === null || (t != 'object' && t != 'function')) {
throw new TypeError('Object required');
}
var keys = [];
iterateOverObject(obj, function(k,v) {
keys.push(k);
if(fn) fn.call(obj, k);
});
return keys;
}
});
/***
* Array module
*
***/
// Basic array internal methods
function arrayEach(arr, fn, index, loop, sparse) {
var length, index, i;
checkCallback(fn);
i = toIntegerWithDefault(index, 0);
length = loop === true ? arr.length + i : arr.length;
while(i < length) {
index = i % arr.length;
if(!(index in arr) && sparse === true) {
return iterateOverSparseArray(arr, fn, i, loop);
} else if(fn.call(arr, arr[index], index, arr) === false) {
break;
}
i++;
}
}
function arrayFind(arr, f, fromIndex, loop, returnIndex) {
var result, index;
arrayEach(arr, function(el, i, arr) {
if(multiMatch(el, f, arr, [i, arr])) {
result = el;
index = i;
return false;
}
}, fromIndex, loop);
return returnIndex ? index : result;
}
function arrayUnique(arr) {
var result = [];
arr.each(function(el) {
if(arrayFind(result, el) === undefined) result.push(el);
});
return result;
}
function arrayFlatten(arr) {
var result = [];
arrayEach(arr, function(el) {
if(Array.isArray(el)) {
result = result.concat(arrayFlatten(el));
} else {
result.push(el);
}
});
return result;
}
// ECMA5 methods
function toIntegerWithDefault(i, d) {
if(isNaN(i)) {
return d;
} else {
return parseInt(i >> 0);
}
}
function isArrayIndex(arr, i) {
return i in arr && toUInt32(i) == i && i != 0xffffffff;
}
function toUInt32(i) {
return i >>> 0;
}
function checkCallback(fn) {
if(!fn || !fn.call) {
throw new TypeError('Callback is not callable');
}
}
function checkFirstArgumentExists(args) {
if(args.length === 0) {
throw new TypeError('First argument must be defined');
}
}
// Support methods
function iterateOverSparseArray(arr, fn, fromIndex, loop) {
var indexes = [], i;
for(i in arr) {
if(isArrayIndex(arr, i) && i >= fromIndex) {
indexes.push(i.toNumber());
}
}
indexes.sort().each(function(index) {
return fn.call(arr, arr[index], index, arr);
});
return arr;
}
function getMinOrMax(obj, args, which, el) {
var max = which === 'max', min = which === 'min';
var edge = max ? -Infinity : Infinity;
var result = [];
iterateOverObject(obj, function(key) {
var entry = obj[key];
var test = transformArgument(args, entry, el);
if(test === undefined || test === null) {
return;
} else if(test === edge) {
result.push(entry);
} else if((max && test > edge) || (min && test < edge)) {
result = [entry];
edge = test;
}
});
return result;
}
extend(Array, false, false, {
/***
*
* @method Array.create(<obj1>, <obj2>, ...)
* @returns Array
* @short Alternate array constructor.
* @extra This method will create a single arrray by calling %concat% on all arguments passed. In addition to ensuring that an unknown variable is in a single, flat array (the standard constructor will create nested arrays, this one will not), it is also a useful shorthand to convert a function's arguments object into a standard array.
* @example
*
* Array.create('one', true, 3) -> ['one', true, 3]
* Array.create(['one', true, 3]) -> ['one', true, 3]
+ Array.create(function(n) {
* return arguments;
* }('howdy', 'doody'));
*
***/
'create': function(obj) {
var result = [];
multiArgs(arguments, function(a) {
if(a && a.callee) a = Array.prototype.slice.call(a);
result = result.concat(a);
});
return result;
},
/***
*
* @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 instance(obj, 'Array');
}
});
extend(Array, true, function() { var a = arguments; return a.length === 0 || Object.isFunction(a[0]); }, {
/***
* @method every(<f>, [scope])
* @returns Boolean
* @short Returns true if all elements in the array match <f>.
* @extra [scope] is the %this% object. In addition to providing this method for browsers that don't support it natively, this enhanced method also directly accepts strings, numbers, deep objects, and arrays for <f>. %all% is provided an alias.
* @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(f, scope) {
var length = this.length, index = 0;
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && !multiMatch(this[index], f, scope, [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. In addition to providing this method for browsers that don't support it natively, this enhanced method also directly accepts strings, numbers, deep objects, and arrays for <f>. %any% and %has% are provided as aliases.
* @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(f, scope) {
var length = this.length, index = 0;
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && multiMatch(this[index], f, scope, [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. 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. %collect% is provided as an alias.
* @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(map, scope) {
var length = this.length, index = 0, result = new Array(length);
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this) {
result[index] = transformArgument(arguments, this[index], scope, [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 enhanced method also directly accepts strings, numbers, deep objects, and arrays for <f>.
* @example
*
+ [1,2,3].filter(function(n) {
* return n > 1;
* });
* [1,2,2,4].filter(2) -> 2
*
***/
'filter': function(f, scope) {
var length = this.length, index = 0, result = [];
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && multiMatch(this[index], f, scope, [index, this])) {
result.push(this[index]);
}
index++;
}
return result;
}
});
extend(Array, true, false, {
/***
* @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 %find% method instead.
* @example
*
* [1,2,3].indexOf(3) -> 1
* [1,2,3].indexOf(7) -> -1
*
***/
'indexOf': function(search, fromIndex) {
var length = this.length, index = toIntegerWithDefault(fromIndex, 0);
if(Object.isString(this)) {
return this.indexOf(search, fromIndex);
}
if(index < 0) {
index = Math.max(length + index, 0);
}
if(length == 0 || index > length) {
return -1;
}
while(index < length) {
if(index in this && this[index] === search) {
return index;
}
index++;
}
return -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, fromIndex) {
var length = this.length, index = toIntegerWithDefault(fromIndex, length);
if(Object.isString(this)) {
return this.lastIndexOf(search, fromIndex);
}
if(index < 0) {
index = length + index;
}
if(length == 0 || index < 0) {
return -1;
}
while(index >= 0) {
if(index in this && this[index] === search) {
return index;
}
index--;
}
return -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, scope) {
var length = this.length, index = 0;
checkCallback(fn);
while(index < length) {
if(index in this) {
fn.call(scope, this[index], index, this);
}
index++;
}
},
/***
* @method reduce([fn], [init])
* @returns Mixed
* @short Reduces the array to a single result.
* @extra By default this method calls [fn] n - 1 times, where n is the length of the array. On the first call it is passed the first and second elements in the array. The result of that callback will then be passed into the next iteration until it reaches the end, where the accumulated value will be returned as the final result. If [init] is passed, it will call [fn] one extra time in the beginning passing in [init] along with the first element. This method is only provided for those browsers that do not support it natively.
* @example
*
+ [1,2,3,4].reduce(function(a, b) {
* return a + b;
* });
+ [1,2,3,4].reduce(function(a, b) {
* return a + b;
* }, 100);
*
***/
'reduce': function(fn, init) {
var length = this.length, index = 0, initialValue = arguments.length > 1 && init, result;
checkCallback(fn);
if(length == 0 && !initialValue) {
throw new TypeError('Reduce called on empty array with no initial value');
} else if(initialValue) {
result = initialValue;
} else {
result = this[index];
index++;
}
while(index < length) {
if(index in this) {
result = fn.call(undefined, result, this[index], index, this);
}
index++;
}
return result;
},
/***
* @method reduceRight([fn], [init])
* @returns Mixed
* @short Reduces the array to a single result by stepping through it from the right.
* @extra By default this method calls [fn] n - 1 times, where n is the length of the array. On the first call it is passed the last and second to last elements in the array. The result of that callback will then be passed into the next iteration until it reaches the beginning, where the accumulated value will be returned as the final result. If [init] is passed, it will call [fn] one extra time in the beginning passing in [init] along with the last element. This method is only provided for those browsers that do not support it natively.
* @example
*
+ [1,2,3,4].reduceRight(function(a, b) {
* return a - b;
* });
*
***/
'reduceRight': function(fn, init) {
var length = this.length, index = length - 1, initialValue = arguments.length > 1 && init, result;
checkCallback(fn);
if(length == 0 && !initialValue) {
throw new TypeError('Reduce called on empty array with no initial value');
} else if(initialValue) {
result = initialValue;
} else {
result = this[index];
index--;
}
while(index >= 0) {
if(index in this) {
result = fn.call(undefined, result, this[index], index, this);
}
index--;
}
return result;
},
/***
* @method each(<fn>, [index] = 0, [loop] = false)
* @returns Array
* @short Runs <fn> against elements in the array.