forked from romancow/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.js
1092 lines (1015 loc) · 30.3 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';
/***
* @module Array
* @description Array manipulation and traversal, alphanumeric sorting and collation.
*
***/
var HALF_WIDTH_NINE = 0x39;
var FULL_WIDTH_NINE = 0xff19;
// Undefined array elements in < IE8 will not be visited by concat
// and so will not be copied. This means that non-sparse arrays will
// become sparse, so detect for this here.
var HAS_CONCAT_BUG = !('0' in [].concat(undefined).concat());
var ARRAY_OPTIONS = {
'sortIgnore': null,
'sortNatural': true,
'sortIgnoreCase': true,
'sortOrder': getSortOrder(),
'sortCollate': collateStrings,
'sortEquivalents': getSortEquivalents()
};
/***
* @method getOption(<name>)
* @returns Mixed
* @accessor
* @short Gets an option used interally by Array.
* @extra Current options are for sorting strings with `sortBy`.
*
* @options
*
* sortIgnore A regex to ignore when sorting. An example usage of this
* option would be to ignore numbers in a list to instead
* sort by the first text that appears. Default is `null`.
*
* sortIgnoreCase A boolean that ignores case when sorting.
* Default is `true`.
*
* sortNatural A boolean that turns on natural sorting. "Natural" means
* that numerals like "10" will be sorted after "9" instead
* of after "1". Default is `true`.
*
* sortOrder A string of characters to use as the base sort order. The
* default is an order natural to most major world languages.
*
* sortEquivalents A table of equivalent characters used when sorting. The
* default produces a natural sort order for most world
* languages, however can be modified for others. For
* example, setting "ä" and "ö" to `null` in the table would
* produce a Scandanavian sort order.
*
* sortCollate The collation function used when sorting strings. The
* default function produces a natural sort order that can
* be customized with the other "sort" options. Overriding
* the function directly here will also override these
* options.
*
* @example
*
* Sugar.Array.getOption('sortNatural')
*
***
* @method setOption(<name>, <value>)
* @accessor
* @short Sets an option used interally by Array.
* @extra Current options are for sorting strings with `sortBy`. If <value> is
* `null`, the default value will be restored.
*
* @options
*
* sortIgnore A regex to ignore when sorting. An example usage of this
* option would be to ignore numbers in a list to instead
* sort by the first text that appears. Default is `null`.
*
* sortIgnoreCase A boolean that ignores case when sorting.
* Default is `true`.
*
* sortNatural A boolean that turns on natural sorting. "Natural" means
* that numerals like "10" will be sorted after "9" instead
* of after "1". Default is `true`.
*
* sortOrder A string of characters to use as the base sort order. The
* default is an order natural to most major world languages.
*
* sortEquivalents A table of equivalent characters used when sorting. The
* default produces a natural sort order for most world
* languages, however can be modified for others. For
* example, setting "ä" and "ö" to `null` in the table would
* produce a Scandanavian sort order. Note that setting this
* option to `null` will restore the default table, but any
* mutations made to that table will persist.
*
* sortCollate The collation function used when sorting strings. The
* default function produces a natural sort order that can
* be customized with the other "sort" options. Overriding
* the function directly here will also override these
* options.
*
* @example
*
* Sugar.Array.setOption('sortIgnore', /^\d+\./)
* Sugar.Array.setOption('sortIgnoreCase', false)
*
***/
var _arrayOptions = defineOptionsAccessor(sugarArray, ARRAY_OPTIONS);
function setArrayChainableConstructor() {
setChainableConstructor(sugarArray, arrayCreate);
}
function isArrayOrInherited(obj) {
return obj && obj.constructor && isArray(obj.constructor.prototype);
}
function arrayCreate(obj, clone) {
var arr;
if (isArrayOrInherited(obj)) {
arr = clone ? arrayClone(obj) : obj;
} else if (isObjectType(obj) || isString(obj)) {
arr = Array.from(obj);
} else if (isDefined(obj)) {
arr = [obj];
}
return arr || [];
}
function arrayClone(arr) {
var clone = [];
forEach(arr, function(el, i) {
clone[i] = el;
});
return clone;
}
function arrayConcat(arr1, arr2) {
if (HAS_CONCAT_BUG) {
return arraySafeConcat(arr1, arr2);
}
return arr1.concat(arr2);
}
// Avoids issues with [undefined] in < IE9
function arrayWrap(obj) {
var arr = [];
arr.push(obj);
return arr;
}
// Avoids issues with concat in < IE8
function arraySafeConcat(arr1, arr2) {
var result = arrayClone(arr1), len = result.length;
forEach(arr2, function(el, i) {
result[len + i] = el;
});
return result;
}
function arrayAppend(arr, el, index) {
var spliceArgs;
index = +index;
if (isNaN(index)) {
index = arr.length;
}
spliceArgs = [index, 0];
if (isDefined(el)) {
spliceArgs = spliceArgs.concat(el);
}
arr.splice.apply(arr, spliceArgs);
return arr;
}
function arrayRemove(arr, f) {
var matcher = getMatcher(f), i = 0;
while(i < arr.length) {
if (matcher(arr[i], i, arr)) {
arr.splice(i, 1);
} else {
i++;
}
}
return arr;
}
function arrayExclude(arr, f) {
var result = [], matcher = getMatcher(f);
for (var i = 0; i < arr.length; i++) {
if (!matcher(arr[i], i, arr)) {
result.push(arr[i]);
}
}
return result;
}
function arrayUnique(arr, map) {
var result = [], o = {}, transformed;
forEach(arr, function(el, i) {
transformed = map ? mapWithShortcuts(el, map, arr, [el, i, arr]) : el;
if (!checkForElementInHashAndSet(o, transformed)) {
result.push(el);
}
});
return result;
}
function arrayFlatten(arr, level, current) {
level = level || Infinity;
current = current || 0;
var result = [];
forEach(arr, function(el) {
if (isArray(el) && current < level) {
result = result.concat(arrayFlatten(el, level, current + 1));
} else {
result.push(el);
}
});
return result;
}
function arrayCompact(arr, all) {
return filter(arr, function(el) {
return el || (!all && el != null && el.valueOf() === el.valueOf());
});
}
function arrayShuffle(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 arrayGroupBy(arr, map, fn) {
var result = {}, key;
forEach(arr, function(el, index) {
key = mapWithShortcuts(el, map, arr, [el, index, arr]);
if (!hasOwn(result, key)) {
result[key] = [];
}
result[key].push(el);
});
if (fn) {
forEachProperty(result, fn);
}
return result;
}
function arrayIntersectOrSubtract(arr1, arr2, subtract) {
var result = [], o = {};
if (!isArray(arr2)) {
arr2 = arrayWrap(arr2);
}
forEach(arr2, function(el) {
checkForElementInHashAndSet(o, el);
});
forEach(arr1, function(el) {
var stringified = stringify(el),
isReference = !canCompareValue(el);
// Add the result to the array if:
// 1. Subtracting intersections or doesn't already exist in the result
// 2. Exists and we're adding, or doesn't exist and we're removing.
if (elementExistsInHash(o, stringified, el, isReference) !== subtract) {
discardElementFromHash(o, stringified, el, isReference);
result.push(el);
}
});
return result;
}
// Array diff helpers
function elementExistsInHash(obj, key, el, isReference) {
var exists;
if (isReference) {
if (!hasOwn(obj, key)) {
obj[key] = [];
}
exists = indexOf(obj[key], el) !== -1;
} else {
exists = hasOwn(obj, key);
}
return exists;
}
function checkForElementInHashAndSet(obj, el) {
var stringified = stringify(el),
isReference = !canCompareValue(el),
exists = elementExistsInHash(obj, stringified, el, isReference);
if (isReference) {
obj[stringified].push(el);
} else {
obj[stringified] = el;
}
return exists;
}
function discardElementFromHash(obj, key, element, isReference) {
var arr, i = 0;
if (isReference) {
arr = getOwn(obj, key);
while(i < arr.length) {
if (arr[i] === element) {
arr.splice(i, 1);
} else {
i += 1;
}
}
} else {
delete obj[key];
}
}
// Collation helpers
function compareValue(aVal, bVal) {
var cmp, i, collate;
if (isString(aVal) && isString(bVal)) {
collate = _arrayOptions('sortCollate');
return collate(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;
}
}
return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
}
function codeIsNumeral(code) {
return (code >= HALF_WIDTH_ZERO && code <= HALF_WIDTH_NINE) ||
(code >= FULL_WIDTH_ZERO && code <= FULL_WIDTH_NINE);
}
function collateStrings(a, b) {
var aValue, bValue, aChar, bChar, aEquiv, bEquiv, index = 0, tiebreaker = 0;
var sortOrder = _arrayOptions('sortOrder');
var sortIgnore = _arrayOptions('sortIgnore');
var sortNatural = _arrayOptions('sortNatural');
var sortIgnoreCase = _arrayOptions('sortIgnoreCase');
var sortEquivalents = _arrayOptions('sortEquivalents');
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 (sortNatural && 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 getOwn(sortEquivalents, chr) || chr;
}
function getSortOrderIndex(chr, sortOrder) {
if (!chr) {
return null;
} else {
return sortOrder.indexOf(chr);
}
}
function getSortOrder() {
var order = 'AÁÀÂÃĄBCĆČÇDĎÐEÉÈĚÊËĘFGĞHıIÍÌİÎÏJKLŁMNŃŇÑOÓÒÔPQRŘSŚŠŞTŤUÚÙŮÛÜVWXYÝZŹŻŽÞÆŒØÕÅÄÖ';
return map(order.split(''), function(str) {
return str + str.toLowerCase();
}).join('');
}
function getSortEquivalents() {
var equivalents = {};
forEach(commaSplit('AÁÀÂÃÄ,CÇ,EÉÈÊË,IÍÌİÎÏ,OÓÒÔÕÖ,Sß,UÚÙÛÜ'), function(set) {
var first = set.charAt(0);
forEach(set.slice(1).split(''), function(chr) {
equivalents[chr] = first;
equivalents[chr.toLowerCase()] = first.toLowerCase();
});
});
return equivalents;
}
defineStatic(sugarArray, {
/***
*
* @method create(<obj>, [clone] = false)
* @returns Array
* @static
* @short Creates an array from an unknown object.
* @extra This method is similar to native `Array.from` but is faster when
* <obj> is already an array. When [clone] is true, the array will be
* shallow cloned. Additionally, it will not fail on `undefined`,
* `null`, or numbers, producing an empty array in the case of
* `undefined` and wrapping <obj> otherwise.
*
* @example
*
* Array.create() -> []
* Array.create(8) -> [8]
* Array.create('abc') -> ['a','b','c']
* Array.create([1,2,3]) -> [1, 2, 3]
* Array.create(undefined) -> []
*
***/
'create': function(obj, clone) {
return arrayCreate(obj, clone);
},
/***
*
* @method construct(<n>, <fn>)
* @returns Array
* @static
* @short Constructs an array of <n> length from the values of <fn>.
*
* @callback fn
*
* i The index of the current iteration.
*
* @example
*
* Array.construct(4, function(i) {
* return i * i;
* }); -> [0, 1, 4]
*
***/
'construct': function(n, fn) {
return Array.from(new Array(+n), function(el, i) {
return fn && fn(i);
});
}
});
defineInstance(sugarArray, {
/***
* @method isEmpty()
* @returns Boolean
* @short Returns true if the array has a length of zero.
*
* @example
*
* [].isEmpty() -> true
* ['a'].isEmpty() -> false
*
***/
'isEmpty': function(arr) {
return arr.length === 0;
},
/***
* @method isEqual(<arr>)
* @returns Boolean
* @short Returns true if the array is equal to <arr>.
* @extra Objects in the array are considered equal if they are not obserably
* distinguishable. This method is an instance alias for
* `Object.isEqual()`.
*
* @example
*
* ['a','b'].isEqual(['a','b']) -> true
* ['a','b'].isEqual(['a','c']) -> false
* [{a:'a'}].isEqual([{a:'a'}]) -> true
* [5].isEqual([Object(5)]) -> false
*
***/
'isEqual': function(a, b) {
return isEqual(a, b);
},
/***
* @method clone()
* @returns Array
* @short Creates a shallow clone of the array.
*
* @example
*
* [1,2,3].clone() -> [1,2,3]
*
***/
'clone': function(arr) {
return arrayClone(arr);
},
/***
* @method at(<index>, [loop] = false)
* @returns Mixed
* @short Gets the element(s) at <index>.
* @extra When [loop] is true, overshooting the end of the array will begin
* counting from the other end. <index> may be negative. If <index> is
* an array, multiple elements will be returned.
*
* @example
*
* [1,2,3].at(0) -> 1
* [1,2,3].at(2) -> 3
* [1,2,3].at(4) -> undefined
* [1,2,3].at(4, true) -> 2
* [1,2,3].at(-1) -> 3
* [1,2,3].at([0, 1]) -> [1, 2]
*
***/
'at': function(arr, index, loop) {
return getEntriesForIndexes(arr, index, loop);
},
/***
* @method add(<item>, [index])
* @returns Array
* @short Adds <item> to the array and returns the result as a new array.
* @extra If <item> is also an array, it will be concatenated instead of
* inserted. [index] will control where <item> is added. Use `append`
* to modify the original array.
*
* @example
*
* [1,2,3,4].add(5) -> [1,2,3,4,5]
* [1,2,3,4].add(8, 1) -> [1,8,2,3,4]
* [1,2,3,4].add([5,6,7]) -> [1,2,3,4,5,6,7]
*
***/
'add': function(arr, item, index) {
return arrayAppend(arrayClone(arr), item, index);
},
/***
* @method subtract(<item>)
* @returns Array
* @short Subtracts <item> from the array and returns the result as a new array.
* @extra If <item> is also an array, all elements in it will be removed. In
* addition to primitives, this method will also deep-check objects for
* equality.
*
* @example
*
* [1,3,5].subtract([5,7,9]) -> [1,3]
* ['a','b'].subtract(['b','c']) -> ['a']
* [1,2,3].subtract(2) -> [1,3]
*
***/
'subtract': function(arr1, arr2) {
return arrayIntersectOrSubtract(arr1, arr2, true);
},
/***
* @method append(<item>, [index])
* @returns Array
* @short Appends <item> to the array.
* @extra If <item> is also an array, it will be concatenated instead of
* inserted. This method modifies the array! Use `add` to create a new
* array. Additionally, `insert` is provided as an alias that reads
* better when using an index.
*
* @example
*
* [1,2,3,4].append(5) -> [1,2,3,4,5]
* [1,2,3,4].append([5,6,7]) -> [1,2,3,4,5,6,7]
* [1,2,3,4].append(8, 1) -> [1,8,2,3,4]
*
***/
'append': function(arr, item, index) {
return arrayAppend(arr, item, index);
},
/***
* @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 modify the array!
*
* @example
*
* ['a','b','c'].removeAt(0) -> ['b','c']
* [1,2,3,4].removeAt(1, 2) -> [1, 4]
*
***/
'removeAt': function(arr, start, end) {
if (isUndefined(start)) return arr;
if (isUndefined(end)) end = start;
arr.splice(start, end - start + 1);
return arr;
},
/***
* @method unique([map])
* @returns Array
* @short Removes all duplicate elements in the array.
* @extra [map] may be a function returning the value to be uniqued or a
* string acting as a shortcut. This is most commonly used when you
* only need to check a single field that can ensure the object's
* uniqueness (such as an `id` field). If [map] is not passed, then
* objects will be deep checked for equality. Supports
* `deep properties`.
*
* @callback map
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,2,3].unique() -> [1,2,3]
* [{a:'a'},{a:'a'}].unique() -> [{a:'a'}]
*
* users.unique(function(user) {
* return user.id;
* }); -> users array uniqued by id
*
* users.unique('id') -> users array uniqued by id
*
***/
'unique': function(arr, map) {
return arrayUnique(arr, 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 to
* that depth.
*
* @example
*
* [[1], 2, [3]].flatten() -> [1,2,3]
* [[1],[],2,3].flatten() -> [1,2,3]
*
***/
'flatten': function(arr, limit) {
return arrayFlatten(arr, limit);
},
/***
* @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(arr, num) {
if (isUndefined(num)) return arr[0];
if (num < 0) num = 0;
return arr.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(arr, num) {
if (isUndefined(num)) return arr[arr.length - 1];
var start = arr.length - num < 0 ? 0 : arr.length - num;
return arr.slice(start);
},
/***
* @method from(<index>)
* @returns Array
* @short Returns a slice of the array from <index>.
*
* @example
*
* ['a','b','c'].from(1) -> ['b','c']
* ['a','b','c'].from(2) -> ['c']
*
***/
'from': function(arr, num) {
return arr.slice(num);
},
/***
* @method to(<index>)
* @returns Array
* @short Returns a slice of the array up to <index>.
*
* @example
*
* ['a','b','c'].to(1) -> ['a']
* ['a','b','c'].to(2) -> ['a','b']
*
***/
'to': function(arr, num) {
if (isUndefined(num)) num = arr.length;
return arr.slice(0, num);
},
/***
* @method compact([all] = false)
* @returns Array
* @short Removes all instances of `undefined`, `null`, and `NaN` from the array.
* @extra If [all] is `true`, all "falsy" elements will be removed. This
* includes empty strings, `0`, and `false`.
*
* @example
*
* [1,null,2,undefined,3].compact() -> [1,2,3]
* [1,'',2,false,3].compact() -> [1,'',2,false,3]
* [1,'',2,false,3].compact(true) -> [1,2,3]
* [null, [null, 'bye']].compact() -> ['hi', [null, 'bye']]
*
***/
'compact': function(arr, all) {
return arrayCompact(arr, all);
},
/***
* @method groupBy(<map>, [fn])
* @returns Object
* @short Groups the array by <map>.
* @extra Will return an object with keys equal to the grouped values. <map>
* may be a mapping function, or a string acting as a shortcut. <map>
* supports `deep properties`. Optionally calls [fn] for each group.
*
* @callback map
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @callback fn
*
* key The unique key of the current group.
* arr The current group as an array.
* obj A reference to the object.
*
* @example
*
* ['a','aa','aaa'].groupBy('length') -> { 1: ['a'], 2: ['aa'], 3: ['aaa'] }
*
* users.groupBy(function(n) {
* return n.age;
* }); -> users array grouped by age
*
* users.groupBy('age', function(age, users) {
* // iterates each grouping
* });
*
***/
'groupBy': function(arr, map, fn) {
return arrayGroupBy(arr, map, fn);
},
/***
* @method inGroups(<num>, [padding])
* @returns Array
* @short Groups the array into <num> arrays.
* @extra If specified, [padding] will be added to the last array to be of
* equal length.
*
* @example
*
* [1,2,3,4,5,6,7].inGroups(3) -> [[1,2,3],[4,5,6],[7]]
* [1,2,3,4,5,6,7].inGroups(3, 0) -> [[1,2,3],[4,5,6],[7,0,0]]
*
***/
'inGroups': function(arr, num, padding) {
var pad = isDefined(padding);
var result = [];
var divisor = ceil(arr.length / num);
simpleRepeat(num, function(i) {
var index = i * divisor;
var group = arr.slice(index, index + divisor);
if (pad && group.length < divisor) {
simpleRepeat(divisor - group.length, function() {
group.push(padding);
});
}
result.push(group);
});
return result;
},
/***
* @method inGroupsOf(<num>, [padding] = null)
* @returns Array
* @short Groups the array into arrays of <num> elements each.
* @extra [padding] will be added to the last array to be of equal length.
*
* @example
*
* [1,2,3,4,5,6,7].inGroupsOf(4) -> [ [1,2,3,4], [5,6,7] ]
* [1,2,3,4,5,6,7].inGroupsOf(4, 0) -> [ [1,2,3,4], [5,6,7,0] ]
*
***/
'inGroupsOf': function(arr, num, padding) {
var result = [], len = arr.length, group;
if (len === 0 || num === 0) return arr;
if (isUndefined(num)) num = 1;
if (isUndefined(padding)) padding = null;
simpleRepeat(ceil(len / num), function(i) {
group = arr.slice(num * i, num * i + num);
while(group.length < num) {
group.push(padding);
}
result.push(group);
});
return result;
},
/***
* @method shuffle()
* @returns Array
* @short Returns a copy of the array with the elements randomized.
* @extra Uses Fisher-Yates algorithm.
*
* @example
*
* [1,2,3,4].shuffle() -> [?,?,?,?]
*
***/
'shuffle': function(arr) {
return arrayShuffle(arr);
},
/***
* @method sample([num] = 1, [remove] = false)
* @returns Mixed
* @short Returns a random element from the array.
* @extra If [num] is passed, will return an array of [num] elements. If
* [remove] is true, sampled elements will also be removed from the
* array. [remove] can also be passed in place of [num].
*
* @example
*
* [1,2,3,4,5].sample() -> // Random element
* [1,2,3,4,5].sample(1) -> // Array of 1 random element
* [1,2,3,4,5].sample(3) -> // Array of 3 random elements
*
***/
'sample': function(arr, arg1, arg2) {
var result = [], num, remove, single;
if (isBoolean(arg1)) {
remove = arg1;
} else {
num = arg1;
remove = arg2;
}
if (isUndefined(num)) {
num = 1;
single = true;
}
if (!remove) {
arr = arrayClone(arr);
}
num = min(num, arr.length);
for (var i = 0, index; i < num; i++) {
index = trunc(Math.random() * arr.length);
result.push(arr[index]);
arr.splice(index, 1);
}
return single ? result[0] : result;
},
/***
* @method sortBy(<map>, [desc] = false)
* @returns Array
* @short Enhanced sorting function that will sort the array by <map>.
* @extra <map> may be a function, a string acting as a shortcut, an array
* (comparison by multiple values), or blank (direct comparison of
* array values). <map> supports `deep properties`. [desc] will sort
* the array in descending order. When the field being sorted on is
* a string, the resulting order will be determined by an internal
* collation algorithm that is optimized for major Western languages,
* but can be customized using sorting accessors such as `sortIgnore`.
* This method will modify the array!
*
* @callback map
*
* el An array element.
*
* @example
*
* ['world','a','new'].sortBy('length') -> ['a','new','world']
* ['world','a','new'].sortBy('length', true) -> ['world','new','a']
* users.sortBy(function(n) {
* return n.age;
* }); -> users array sorted by age
* users.sortBy('age') -> users array sorted by age
*
***/
'sortBy': function(arr, map, desc) {
arr.sort(function(a, b) {
var aProperty = mapWithShortcuts(a, map, arr, [a]);
var bProperty = mapWithShortcuts(b, map, arr, [b]);
return compareValue(aProperty, bProperty) * (desc ? -1 : 1);
});
return arr;
},
/***
* @method remove(<search>)
* @returns Array
* @short Removes any element in the array that matches <search>.
* @extra This method will modify the array! Use `exclude` for a
* non-destructive alias. This method implements `enhanced matching`.
*
* @callback search
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3].remove(3) -> [1,2]
* ['a','b','c'].remove(/b/) -> ['a','c']
* [{a:1},{b:2}].remove(function(n) {
* return n['a'] == 1;
* }); -> [{b:2}]
*
***/
'remove': function(arr, f) {
return arrayRemove(arr, f);
},
/***
* @method exclude(<search>)
* @returns Array
* @short Returns a new array with every element that does not match <search>.
* @extra This method can be thought of as the inverse of `Array#filter`. It
* will not modify the original array, Use `remove` to modify the
* array in place. Implements `enhanced matching`.
*
* @callback search
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3].exclude(3) -> [1,2]
* ['a','b','c'].exclude(/b/) -> ['a','c']