forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.js
1363 lines (1254 loc) · 43.2 KB
/
array.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
'use strict';
/***
* @package Array
* @dependency core
* @description Array manipulation and traversal, "fuzzy matching" against elements, alphanumeric sorting and collation, enumerable methods on Object.
*
***/
function regexMatcher(reg) {
reg = regexp(reg);
return function (el) {
return reg.test(el);
}
}
function dateMatcher(d) {
var ms = d.getTime();
return function (el) {
return !!(el && el.getTime) && el.getTime() === ms;
}
}
function functionMatcher(fn) {
return function (el, i, arr) {
// Return true up front if match by reference
return el === fn || fn.call(this, el, i, arr);
}
}
function invertedArgsFunctionMatcher(fn) {
return function (value, key, obj) {
// Return true up front if match by reference
return value === fn || fn.call(obj, key, value, obj);
}
}
function fuzzyMatcher(obj, isObject) {
var matchers = {};
return function (el, i, arr) {
var key;
if (!isObjectType(el)) {
return false;
}
for(key in obj) {
matchers[key] = matchers[key] || getMatcher(obj[key], isObject);
if (matchers[key].call(arr, el[key], i, arr) === false) {
return false;
}
}
return true;
}
}
function defaultMatcher(f) {
return function (el) {
return el === f || isEqual(el, f);
}
}
function getMatcher(f, isObject) {
if (isPrimitiveType(f)) {
// Do nothing and fall through to the
// default matcher below.
} else if (isRegExp(f)) {
// Match against a regexp
return regexMatcher(f);
} else if (isDate(f)) {
// Match against a date. isEqual below should also
// catch this but matching directly up front for speed.
return dateMatcher(f);
} else if (isFunction(f)) {
// Match against a filtering function
if (isObject) {
return invertedArgsFunctionMatcher(f);
} else {
return functionMatcher(f);
}
} else if (isPlainObject(f)) {
// Match against a fuzzy hash or array.
return fuzzyMatcher(f, isObject);
}
// Default is standard isEqual
return defaultMatcher(f);
}
function transformArgument(el, map, context, mapArgs) {
if (!map) {
return el;
} else if (map.apply) {
return map.apply(context, mapArgs || []);
} else if (isArray(map)) {
return map.map(function(m) {
return transformArgument(el, m, context, mapArgs);
});
} else if (isFunction(el[map])) {
return el[map].call(el);
} else {
return el[map];
}
}
function compareValue(aVal, bVal) {
var cmp, i;
if (isString(aVal) && isString(bVal)) {
return collateStrings(aVal, bVal);
} else if (isArray(aVal) && isArray(bVal)) {
if (aVal.length < bVal.length) {
return -1;
} else if (aVal.length > bVal.length) {
return 1;
} else {
for(i = 0; i < aVal.length; i++) {
cmp = compareValue(aVal[i], bVal[i]);
if (cmp !== 0) {
return cmp;
}
}
return 0;
}
} else if (aVal < bVal) {
return -1;
} else if (aVal > bVal) {
return 1;
} else {
return 0;
}
}
// Basic array internal methods
function arrayEach(arr, fn, startIndex, loop) {
var index, i, length = +arr.length;
if (startIndex < 0) startIndex = arr.length + startIndex;
i = isNaN(startIndex) ? 0 : startIndex;
if (loop === true) {
length += i;
}
while(i < length) {
index = i % arr.length;
if (!(index in arr)) {
return iterateOverSparseArray(arr, fn, i, loop);
} else if (fn.call(arr, arr[index], index, arr) === false) {
break;
}
i++;
}
}
function iterateOverSparseArray(arr, fn, fromIndex, loop) {
var indexes = [], i;
for(i in arr) {
if (isArrayIndex(arr, i) && i >= fromIndex) {
indexes.push(parseInt(i));
}
}
arrayEach(indexes.sort(), function(index) {
return fn.call(arr, arr[index], index, arr);
});
return arr;
}
function isArrayIndex(arr, i) {
return i in arr && toUInt32(i) == i && i != 0xffffffff;
}
function toUInt32(i) {
return i >>> 0;
}
function arrayFind(arr, f, startIndex, loop, returnIndex, context) {
var result, index, matcher;
if (arr.length > 0) {
matcher = getMatcher(f);
arrayEach(arr, function(el, i) {
if (matcher.call(context, el, i, arr)) {
result = el;
index = i;
return false;
}
}, startIndex, loop);
}
return returnIndex ? index : result;
}
function arrayFindAll(arr, f, index, loop) {
var result = [], matcher;
if (arr.length > 0) {
matcher = getMatcher(f);
arrayEach(arr, function(el, i, arr) {
if (matcher(el, i, arr)) {
result.push(el);
}
}, index, loop);
}
return result;
}
function arrayAdd(arr, el, index) {
if (!isNumber(number(index)) || isNaN(index)) index = arr.length;
array.prototype.splice.apply(arr, [index, 0].concat(el));
return arr;
}
function arrayRemoveElement(arr, f) {
var i = 0, matcher = getMatcher(f);
while(i < arr.length) {
if (matcher(arr[i], i, arr)) {
arr.splice(i, 1);
} else {
i++;
}
}
}
function arrayUnique(arr, map) {
var result = [], o = {}, transformed;
arrayEach(arr, function(el, i) {
transformed = map ? transformArgument(el, map, arr, [el, i, arr]) : el;
if (!checkForElementInHashAndSet(o, transformed)) {
result.push(el);
}
})
return result;
}
function arrayIntersect(arr1, arr2, subtract) {
var result = [], o = {};
arrayEach(arr2, function(el) {
checkForElementInHashAndSet(o, el);
});
arrayEach(arr1, function(el) {
var stringified = stringify(el),
isReference = !objectIsMatchedByValue(el);
// Add the result to the array if:
// 1. We're subtracting intersections or it doesn't already exist in the result and
// 2. It exists in the compared array and we're adding, or it doesn't exist and we're removing.
if (elementExistsInHash(o, stringified, el, isReference) !== subtract) {
discardElementFromHash(o, stringified, el, isReference);
result.push(el);
}
});
return result;
}
function arrayFlatten(arr, level, current) {
level = level || Infinity;
current = current || 0;
var result = [];
arrayEach(arr, function(el) {
if (isArray(el) && current < level) {
result = result.concat(arrayFlatten(el, level, current + 1));
} else {
result.push(el);
}
});
return result;
}
function arrayGroupBy(arr, map, fn) {
var result = {}, key;
arrayEach(arr, function(el, index) {
key = transformArgument(el, map, arr, [el, index, arr]);
if (!result[key]) result[key] = [];
result[key].push(el);
});
if (fn) {
iterateOverObject(result, fn);
}
return result;
}
function arraySum(arr, map) {
if (map) {
arr = sugarArray.map(arr, map);
}
return arr.length > 0 ? arr.reduce(function(a,b) { return a + b; }) : 0;
}
function arrayCompact(arr, all) {
var result = [];
arrayEach(arr, function(el, i) {
if (isArray(el)) {
result.push(arrayCompact(el));
} else if (all && el) {
result.push(el);
} else if (!all && el != null && el.valueOf() === el.valueOf()) {
result.push(el);
}
});
return result;
}
function arrayRandomize(arr) {
arr = arrayClone(arr);
var i = arr.length, j, x;
while(i) {
j = (math.random() * i) | 0;
x = arr[--i];
arr[i] = arr[j];
arr[j] = x;
}
return arr;
}
function arrayClone(arr) {
return simpleMerge([], arr);
}
function isArrayLike(obj) {
return hasProperty(obj, 'length') && !isString(obj) && !isPlainObject(obj);
}
function elementExistsInHash(hash, key, element, isReference) {
var exists = hasOwnProperty(hash, key);
if (isReference) {
if (!hash[key]) {
hash[key] = [];
}
exists = hash[key].indexOf(element) !== -1;
}
return exists;
}
function checkForElementInHashAndSet(hash, element) {
var stringified = stringify(element),
isReference = !objectIsMatchedByValue(element),
exists = elementExistsInHash(hash, stringified, element, isReference);
if (isReference) {
hash[stringified].push(element);
} else {
hash[stringified] = element;
}
return exists;
}
function discardElementFromHash(hash, key, element, isReference) {
var arr, i = 0;
if (isReference) {
arr = hash[key];
while(i < arr.length) {
if (arr[i] === element) {
arr.splice(i, 1);
} else {
i += 1;
}
}
} else {
delete hash[key];
}
}
// Support methods
function getMinOrMax(obj, map, which, all) {
var el,
key,
edge,
test,
result = [],
max = which === 'max',
min = which === 'min',
isArray = array.isArray(obj);
for(key in obj) {
if (!obj.hasOwnProperty(key)) continue;
el = obj[key];
test = transformArgument(el, map, obj, isArray ? [el, parseInt(key), obj] : []);
if (isUndefined(test)) {
throw new TypeError('Cannot compare with undefined');
}
if (test === edge) {
result.push(el);
} else if (isUndefined(edge) || (max && test > edge) || (min && test < edge)) {
result = [el];
edge = test;
}
}
if (!isArray) result = arrayFlatten(result, 1);
return all ? result : result[0];
}
// Alphanumeric collation helpers
function collateStrings(a, b) {
var aValue, bValue, aChar, bChar, aEquiv, bEquiv, index = 0, tiebreaker = 0;
var sortIgnore = sugarArray[AlphanumericSortIgnore];
var sortIgnoreCase = sugarArray[AlphanumericSortIgnoreCase];
var sortEquivalents = sugarArray[AlphanumericSortEquivalents];
var sortOrder = sugarArray[AlphanumericSortOrder];
var naturalSort = sugarArray[AlphanumericSortNatural];
a = getCollationReadyString(a, sortIgnore, sortIgnoreCase);
b = getCollationReadyString(b, sortIgnore, sortIgnoreCase);
do {
aChar = getCollationCharacter(a, index, sortEquivalents);
bChar = getCollationCharacter(b, index, sortEquivalents);
aValue = getSortOrderIndex(aChar, sortOrder);
bValue = getSortOrderIndex(bChar, sortOrder);
if (aValue === -1 || bValue === -1) {
aValue = a.charCodeAt(index) || null;
bValue = b.charCodeAt(index) || null;
if (naturalSort && codeIsNumeral(aValue) && codeIsNumeral(bValue)) {
aValue = stringToNumber(a.slice(index));
bValue = stringToNumber(b.slice(index));
}
} else {
aEquiv = aChar !== a.charAt(index);
bEquiv = bChar !== b.charAt(index);
if (aEquiv !== bEquiv && tiebreaker === 0) {
tiebreaker = aEquiv - bEquiv;
}
}
index += 1;
} while(aValue != null && bValue != null && aValue === bValue);
if (aValue === bValue) return tiebreaker;
return aValue - bValue;
}
function getCollationReadyString(str, sortIgnore, sortIgnoreCase) {
if (!isString(str)) str = string(str);
if (sortIgnoreCase) {
str = str.toLowerCase();
}
if (sortIgnore) {
str = str.replace(sortIgnore, '');
}
return str;
}
function getCollationCharacter(str, index, sortEquivalents) {
var chr = str.charAt(index);
return sortEquivalents[chr] || chr;
}
function getSortOrderIndex(chr, sortOrder) {
if (!chr) {
return null;
} else {
return sortOrder.indexOf(chr);
}
}
var AlphanumericSort = 'AlphanumericSort';
var AlphanumericSortOrder = 'AlphanumericSortOrder';
var AlphanumericSortIgnore = 'AlphanumericSortIgnore';
var AlphanumericSortIgnoreCase = 'AlphanumericSortIgnoreCase';
var AlphanumericSortEquivalents = 'AlphanumericSortEquivalents';
var AlphanumericSortNatural = 'AlphanumericSortNatural';
function buildEnhancements() {
var nativeMap = array.prototype.map;
var callbackCheck = function() {
return arguments.length > 0 && !isFunction(arguments[0]);
};
extendSimilar(array, 'every,some,filter,find,findIndex', function(methods, name) {
var nativeFn = array.prototype[name]
methods[name] = function(f) {
var matcher = getMatcher(f);
return nativeFn.call(this, function(el, index, arr) {
return matcher(el, index, arr);
});
}
}, true, callbackCheck);
extend(array, {
'map': function(map, context) {
var arr = this;
if (arguments.length < 2) {
context = arr;
}
return nativeMap.call(arr, function(el, index) {
return transformArgument(el, map, context, [el, index, arr]);
});
}
}, true, callbackCheck);
}
function buildAlphanumericSort() {
var order = 'AÁÀÂÃĄBCĆČÇDĎÐEÉÈĚÊËĘFGĞHıIÍÌİÎÏJKLŁMNŃŇÑOÓÒÔPQRŘSŚŠŞTŤUÚÙŮÛÜVWXYÝZŹŻŽÞÆŒØÕÅÄÖ';
var equiv = 'AÁÀÂÃÄ,CÇ,EÉÈÊË,IÍÌİÎÏ,OÓÒÔÕÖ,Sß,UÚÙÛÜ';
sugarArray[AlphanumericSortOrder] = order.split('').map(function(str) {
return str + str.toLowerCase();
}).join('');
var equivalents = {};
arrayEach(equiv.split(','), function(set) {
var equivalent = set.charAt(0);
arrayEach(set.slice(1).split(''), function(chr) {
equivalents[chr] = equivalent;
equivalents[chr.toLowerCase()] = equivalent.toLowerCase();
});
});
sugarArray[AlphanumericSortNatural] = true;
sugarArray[AlphanumericSortIgnoreCase] = true;
sugarArray[AlphanumericSortEquivalents] = equivalents;
}
extend(array, {
/***
*
* @method Array.create(<obj1>, <obj2>, ...)
* @returns Array
* @short Alternate array constructor.
* @extra This method will create a single array 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() {
// Optimized: no leaking arguments
var result = [];
for (var i = 0; i < arguments.length; i++) {
var a = arguments[i];
if (isArgumentsObject(a) || isArrayLike(a)) {
for (var j = 0; j < a.length; j++) {
result.push(a[j]);
}
continue;
}
result = result.concat(a);
}
return result;
}
}, false);
extend(array, {
/***
* @method find(<f>, [context])
* @returns Mixed
* @short Returns the first element that matches <f>.
* @extra [context] is the %this% object if passed. When <f> is a function, will use native implementation if it exists. <f> will also match a string, number, array, object, or alternately test against a function or regex. This method implements %array_matching%.
* @example
*
* [{a:1,b:2},{a:1,b:3},{a:1,b:4}].find(function(n) {
* return n['a'] == 1;
* }); -> {a:1,b:3}
* ['cuba','japan','canada'].find(/^c/) -> 'cuba'
*
***/
'find': function(f) {
var context = arguments[1];
checkCallback(f);
return arrayFind(this, f, 0, false, false, context);
},
/***
* @method findIndex(<f>, [context])
* @returns Number
* @short Returns the index of the first element that matches <f> or -1 if not found.
* @extra [context] is the %this% object if passed. When <f> is a function, will use native implementation if it exists. <f> will also match a string, number, array, object, or alternately test against a function or regex. This method implements %array_matching%.
*
* @example
*
* [1,2,3,4].findIndex(function(n) {
* return n % 2 == 0;
* }); -> 1
* [1,2,3,4].findIndex(3); -> 2
* ['one','two','three'].findIndex(/t/); -> 1
*
***/
'findIndex': function(f) {
var index, context = arguments[1];
checkCallback(f);
index = arrayFind(this, f, 0, false, true, context);
return isUndefined(index) ? -1 : index;
}
}, true, true);
extend(array, {
/***
* @method findFrom(<f>, [index] = 0, [loop] = false)
* @returns Array
* @short Returns any element that matches <f>, beginning from [index].
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. Will continue from index = 0 if [loop] is true. This method implements %array_matching%.
* @example
*
* ['cuba','japan','canada'].findFrom(/^c/, 2) -> 'canada'
*
***/
'findFrom': function(f, index, loop) {
return arrayFind(this, f, index, loop);
},
/***
* @method findIndexFrom(<f>, [index] = 0, [loop] = false)
* @returns Array
* @short Returns the index of any element that matches <f>, beginning from [index].
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. Will continue from index = 0 if [loop] is true. This method implements %array_matching%.
* @example
*
* ['cuba','japan','canada'].findIndexFrom(/^c/, 2) -> 2
*
***/
'findIndexFrom': function(f, index, loop) {
var index = arrayFind(this, f, index, loop, true);
return isUndefined(index) ? -1 : index;
},
/***
* @method findAll(<f>, [index] = 0, [loop] = false)
* @returns Array
* @short Returns all elements that match <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. Starts at [index], and will continue once from index = 0 if [loop] is true. This method implements %array_matching%.
* @example
*
* [{a:1,b:2},{a:1,b:3},{a:2,b:4}].findAll(function(n) {
* return n['a'] == 1;
* }); -> [{a:1,b:3},{a:1,b:4}]
* ['cuba','japan','canada'].findAll(/^c/) -> 'cuba','canada'
* ['cuba','japan','canada'].findAll(/^c/, 2) -> 'canada'
*
***/
'findAll': function(f, index, loop) {
return arrayFindAll(this, f, index, loop);
},
/***
* @method count(<f>)
* @returns Number
* @short Counts all elements in the array that match <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. This method implements %array_matching%.
* @example
*
* [1,2,3,1].count(1) -> 2
* ['a','b','c'].count(/b/) -> 1
* [{a:1},{b:2}].count(function(n) {
* return n['a'] > 1;
* }); -> 0
*
***/
'count': function(f) {
if (isUndefined(f)) return this.length;
return arrayFindAll(this, f).length;
},
/***
* @method removeAt(<start>, [end])
* @returns Array
* @short Removes element at <start>. If [end] is specified, removes the range between <start> and [end]. This method will change the array! If you don't intend the array to be changed use %clone% first.
* @example
*
* ['a','b','c'].removeAt(0) -> ['b','c']
* [1,2,3,4].removeAt(1, 3) -> [1]
*
***/
'removeAt': function(start, end) {
if (isUndefined(start)) return this;
if (isUndefined(end)) end = start;
this.splice(start, end - start + 1);
return this;
},
/***
* @method include(<el>, [index])
* @returns Array
* @short Adds <el> to the array.
* @extra This is a non-destructive alias for %add%. It will not change the original array.
* @example
*
* [1,2,3,4].include(5) -> [1,2,3,4,5]
* [1,2,3,4].include(8, 1) -> [1,8,2,3,4]
* [1,2,3,4].include([5,6,7]) -> [1,2,3,4,5,6,7]
*
***/
'include': function(el, index) {
return arrayAdd(arrayClone(this), el, index);
},
/***
* @method exclude([f1], [f2], ...)
* @returns Array
* @short Removes any element in the array that matches [f1], [f2], etc.
* @extra This is a non-destructive alias for %remove%. It will not change the original array. This method implements %array_matching%.
* @example
*
* [1,2,3].exclude(3) -> [1,2]
* ['a','b','c'].exclude(/b/) -> ['a','c']
* [{a:1},{b:2}].exclude(function(n) {
* return n['a'] == 1;
* }); -> [{b:2}]
*
***/
'exclude': function() {
var arr = arrayClone(this);
for (var i = 0; i < arguments.length; i++) {
arrayRemoveElement(arr, arguments[i]);
}
return arr;
},
/***
* @method clone()
* @returns Array
* @short Makes a shallow clone of the array.
* @example
*
* [1,2,3].clone() -> [1,2,3]
*
***/
'clone': function() {
return arrayClone(this);
},
/***
* @method unique([map] = null)
* @returns Array
* @short Removes all duplicate elements in the array.
* @extra [map] may be a function mapping the value to be uniqued on or a string acting as a shortcut. This is most commonly used when you have a key that ensures the object's uniqueness, and don't need to check all fields. This method will also correctly operate on arrays of objects.
* @example
*
* [1,2,2,3].unique() -> [1,2,3]
* [{foo:'bar'},{foo:'bar'}].unique() -> [{foo:'bar'}]
* [{foo:'bar'},{foo:'bar'}].unique(function(obj){
* return obj.foo;
* }); -> [{foo:'bar'}]
* [{foo:'bar'},{foo:'bar'}].unique('foo') -> [{foo:'bar'}]
*
***/
'unique': function(map) {
return arrayUnique(this, map);
},
/***
* @method flatten([limit] = Infinity)
* @returns Array
* @short Returns a flattened, one-dimensional copy of the array.
* @extra You can optionally specify a [limit], which will only flatten that depth.
* @example
*
* [[1], 2, [3]].flatten() -> [1,2,3]
* [['a'],[],'b','c'].flatten() -> ['a','b','c']
*
***/
'flatten': function(limit) {
return arrayFlatten(this, limit);
},
/***
* @method union([a1], [a2], ...)
* @returns Array
* @short Returns an array containing all elements in all arrays with duplicates removed.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].union([5,7,9]) -> [1,3,5,7,9]
* ['a','b'].union(['b','c']) -> ['a','b','c']
*
***/
'union': function() {
// Optimized: no leaking arguments (flat)
var args = [], $i; for($i = 0; $i < arguments.length; $i++) args = args.concat(arguments[$i]);
return arrayUnique(this.concat(args));
},
/***
* @method intersect([a1], [a2], ...)
* @returns Array
* @short Returns an array containing the elements all arrays have in common.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].intersect([5,7,9]) -> [5]
* ['a','b'].intersect('b','c') -> ['b']
*
***/
'intersect': function() {
// Optimized: no leaking arguments (flat)
var args = [], $i; for($i = 0; $i < arguments.length; $i++) args = args.concat(arguments[$i]);
return arrayIntersect(this, args, false);
},
/***
* @method subtract([a1], [a2], ...)
* @returns Array
* @short Subtracts from the array all elements in [a1], [a2], etc.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].subtract([5,7,9]) -> [1,3]
* [1,3,5].subtract([3],[5]) -> [1]
* ['a','b'].subtract('b','c') -> ['a']
*
***/
'subtract': function(a) {
// Optimized: no leaking arguments (flat)
var args = [], $i; for($i = 0; $i < arguments.length; $i++) args = args.concat(arguments[$i]);
return arrayIntersect(this, args, true);
},
/***
* @method at(<index>, [loop] = true)
* @returns Mixed
* @short Gets the element(s) at a given index.
* @extra When [loop] is true, overshooting the end of the array (or the beginning) will begin counting from the other end. As an alternate syntax, passing multiple indexes will get the elements at those indexes.
* @example
*
* [1,2,3].at(0) -> 1
* [1,2,3].at(2) -> 3
* [1,2,3].at(4) -> 2
* [1,2,3].at(4, false) -> null
* [1,2,3].at(-1) -> 3
* [1,2,3].at(0,1) -> [1,2]
*
***/
'at': function() {
// Optimized: no leaking arguments
var args = [], $i; for($i = 0; $i < arguments.length; $i++) args.push(arguments[$i]);
return getEntriesForIndexes(this, args);
},
/***
* @method first([num] = 1)
* @returns Mixed
* @short Returns the first element(s) in the array.
* @extra When <num> is passed, returns the first <num> elements in the array.
* @example
*
* [1,2,3].first() -> 1
* [1,2,3].first(2) -> [1,2]
*
***/
'first': function(num) {
if (isUndefined(num)) return this[0];
if (num < 0) num = 0;
return this.slice(0, num);
},
/***
* @method last([num] = 1)
* @returns Mixed
* @short Returns the last element(s) in the array.
* @extra When <num> is passed, returns the last <num> elements in the array.
* @example
*
* [1,2,3].last() -> 3
* [1,2,3].last(2) -> [2,3]
*
***/
'last': function(num) {
if (isUndefined(num)) return this[this.length - 1];
var start = this.length - num < 0 ? 0 : this.length - num;
return this.slice(start);
},
/***
* @method from(<index>)
* @returns Array
* @short Returns a slice of the array from <index>.
* @example
*
* [1,2,3].from(1) -> [2,3]
* [1,2,3].from(2) -> [3]
*
***/
'from': function(num) {
return this.slice(num);
},
/***
* @method to(<index>)
* @returns Array
* @short Returns a slice of the array up to <index>.
* @example
*
* [1,3,5].to(1) -> [1]
* [1,3,5].to(2) -> [1,3]
*
***/
'to': function(num) {
if (isUndefined(num)) num = this.length;
return this.slice(0, num);
},
/***
* @method min([map], [all] = false)
* @returns Mixed
* @short Returns the element in the array with the lowest value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all min values in an array.
* @example
*
* [1,2,3].min() -> 1
* ['fee','fo','fum'].min('length') -> 'fo'
* ['fee','fo','fum'].min('length', true) -> ['fo']
* ['fee','fo','fum'].min(function(n) {
* return n.length;
* }); -> ['fo']
* [{a:3,a:2}].min(function(n) {
* return n['a'];
* }); -> [{a:2}]
*
***/
'min': function(map, all) {
return getMinOrMax(this, map, 'min', all);
},
/***
* @method max([map], [all] = false)
* @returns Mixed
* @short Returns the element in the array with the greatest value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all max values in an array.
* @example
*
* [1,2,3].max() -> 3
* ['fee','fo','fum'].max('length') -> 'fee'
* ['fee','fo','fum'].max('length', true) -> ['fee']
* [{a:3,a:2}].max(function(n) {
* return n['a'];
* }); -> {a:3}
*
***/
'max': function(map, all) {
return getMinOrMax(this, map, 'max', all);
},
/***
* @method least([map])
* @returns Array
* @short Returns the elements in the array with the least commonly occuring value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut.
* @example
*
* [3,2,2].least() -> [3]
* ['fe','fo','fum'].least('length') -> ['fum']
* [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].least(function(n) {
* return n.age;
* }); -> [{age:35,name:'ken'}]
*
***/
'least': function(map, all) {
return getMinOrMax(arrayGroupBy(this, map), 'length', 'min', all);
},
/***
* @method most([map])
* @returns Array
* @short Returns the elements in the array with the most commonly occuring value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut.
* @example
*
* [3,2,2].most() -> [2]
* ['fe','fo','fum'].most('length') -> ['fe','fo']
* [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].most(function(n) {
* return n.age;
* }); -> [{age:12,name:'bob'},{age:12,name:'ted'}]
*
***/
'most': function(map, all) {
return getMinOrMax(arrayGroupBy(this, map), 'length', 'max', all);
},
/***
* @method sum([map])
* @returns Number
* @short Sums all values in the array.
* @extra [map] may be a function mapping the value to be summed or a string acting as a shortcut.
* @example
*
* [1,2,2].sum() -> 5
* [{age:35},{age:12},{age:12}].sum(function(n) {
* return n.age;
* }); -> 59
* [{age:35},{age:12},{age:12}].sum('age') -> 59
*
***/
'sum': function(map) {
return arraySum(this, map);
},
/***
* @method average([map])
* @returns Number
* @short Gets the mean average for all values in the array.
* @extra [map] may be a function mapping the value to be averaged or a string acting as a shortcut.
* @example
*
* [1,2,3].average() -> 2
* [{age:35},{age:11},{age:11}].average(function(n) {
* return n.age;
* }); -> 19
* [{age:35},{age:11},{age:11}].average('age') -> 19
*
***/
'average': function(map) {
return this.length > 0 ? arraySum(this, map) / this.length : 0;