forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enumerable.js
1500 lines (1411 loc) · 43.4 KB
/
enumerable.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 Enumerable
* @description Counting, mapping, and finding methods on both arrays and objects.
*
***/
function sum(obj, map) {
var sum = 0;
enumerateWithMapping(obj, map, function(val) {
sum += val;
});
return sum;
}
function average(obj, map) {
var sum = 0, count = 0;
enumerateWithMapping(obj, map, function(val) {
sum += val;
count++;
});
// Prevent divide by 0
return sum / (count || 1);
}
function median(obj, map) {
var result = [], middle, len;
enumerateWithMapping(obj, map, function(val) {
result.push(val);
});
len = result.length;
if (!len) return 0;
result.sort(function(a, b) {
// IE7 will throw errors on non-numbers!
return (a || 0) - (b || 0);
});
middle = trunc(len / 2);
return len % 2 ? result[middle] : (result[middle - 1] + result[middle]) / 2;
}
function getMinOrMax(obj, arg1, arg2, max, asObject) {
var result = [], pushVal, edge, all, map;
if (isBoolean(arg1)) {
all = arg1;
map = arg2;
} else {
map = arg1;
}
enumerateWithMapping(obj, map, function(val, key) {
if (isUndefined(val)) {
throw new TypeError('Cannot compare with undefined');
}
pushVal = asObject ? key : obj[key];
if (val === edge) {
result.push(pushVal);
} else if (isUndefined(edge) || (max && val > edge) || (!max && val < edge)) {
result = [pushVal];
edge = val;
}
});
return getReducedMinMaxResult(result, obj, all, asObject);
}
function getLeastOrMost(obj, arg1, arg2, most, asObject) {
var group = {}, refs = [], minMaxResult, result, all, map;
if (isBoolean(arg1)) {
all = arg1;
map = arg2;
} else {
map = arg1;
}
enumerateWithMapping(obj, map, function(val, key) {
var groupKey = serializeInternal(val, refs);
var arr = getOwn(group, groupKey) || [];
arr.push(asObject ? key : obj[key]);
group[groupKey] = arr;
});
minMaxResult = getMinOrMax(group, !!all, 'length', most, true);
if (all) {
result = [];
// Flatten result
forEachProperty(minMaxResult, function(val) {
result = result.concat(val);
});
} else {
result = getOwn(group, minMaxResult);
}
return getReducedMinMaxResult(result, obj, all, asObject);
}
// Support
function getReducedMinMaxResult(result, obj, all, asObject) {
if (asObject && all) {
// The method has returned an array of keys so use this array
// to build up the resulting object in the form we want it in.
return result.reduce(function(o, key) {
o[key] = obj[key];
return o;
}, {});
} else if (result && !all) {
result = result[0];
}
return result;
}
function enumerateWithMapping(obj, map, fn) {
var arrayIndexes = isArray(obj);
forEachProperty(obj, function(val, key) {
if (arrayIndexes) {
if (!isArrayIndex(key)) {
return;
}
key = +key;
}
var mapped = mapWithShortcuts(val, map, obj, [val, key, obj]);
fn(mapped, key);
});
}
/*** @namespace Array ***/
// Flag allowing native array methods to be enhanced
var ARRAY_ENHANCEMENTS_FLAG = 'enhanceArray';
// Enhanced map function
var enhancedMap = buildEnhancedMapping('map');
// Enhanced matcher methods
var enhancedFind = buildEnhancedMatching('find'),
enhancedSome = buildEnhancedMatching('some'),
enhancedEvery = buildEnhancedMatching('every'),
enhancedFilter = buildEnhancedMatching('filter'),
enhancedFindIndex = buildEnhancedMatching('findIndex');
function arrayNone() {
return !enhancedSome.apply(this, arguments);
}
function arrayCount(arr, f) {
if (isUndefined(f)) {
return arr.length;
}
return enhancedFilter.apply(this, arguments).length;
}
// Enhanced methods
function buildEnhancedMapping(name) {
return wrapNativeArrayMethod(name, enhancedMapping);
}
function buildEnhancedMatching(name) {
return wrapNativeArrayMethod(name, enhancedMatching);
}
function enhancedMapping(map, context) {
if (isFunction(map)) {
return map;
} else if (map) {
return function(el, i, arr) {
return mapWithShortcuts(el, map, context, [el, i, arr]);
};
}
}
function enhancedMatching(f) {
var matcher;
if (isFunction(f)) {
return f;
}
matcher = getMatcher(f);
return function(el, i, arr) {
return matcher(el, i, arr);
};
}
function wrapNativeArrayMethod(methodName, wrapper) {
var nativeFn = Array.prototype[methodName];
return function(arr, f, context, argsLen) {
var args = new Array(2);
assertArgument(argsLen > 0);
args[0] = wrapper(f, context);
args[1] = context;
return nativeFn.apply(arr, args);
};
}
/***
* @method [fn]FromIndex(startIndex, [loop], ...)
* @returns Mixed
* @short Runs native array functions beginning from `startIndex`.
* @extra If [loop] is `true`, once the end of the array has been reached,
* iteration will continue from the start of the array up to
* `startIndex - 1`. If [loop] is false it can be omitted. Standard
* arguments are then passed which will be forwarded to the native
* methods. When available, methods are always `enhanced`. This includes
* `deep properties` for `map`, and `enhanced matching` for `some`,
* `every`, `filter`, `find`, and `findIndex`. Note also that
* `forEachFromIndex` is optimized for sparse arrays and may be faster
* than native `forEach`.
*
* @set
* mapFromIndex
* forEachFromIndex
* filterFromIndex
* someFromIndex
* everyFromIndex
* reduceFromIndex
* reduceRightFromIndex
* findFromIndex
* findIndexFromIndex
*
* @example
*
* users.mapFromIndex(2, 'name');
* users.mapFromIndex(2, true, 'name');
* names.forEachFromIndex(10, log);
* names.everyFromIndex(15, /^[A-F]/);
*
* @signature [fn]FromIndex(startIndex, ...)
* @param {number} startIndex
* @param {boolean} loop
*
***/
function buildFromIndexMethods() {
var methods = {
'forEach': {
base: forEachAsNative
},
'map': {
wrapper: enhancedMapping
},
'some every': {
wrapper: enhancedMatching
},
'findIndex': {
wrapper: enhancedMatching,
result: indexResult
},
'reduce': {
apply: applyReduce
},
'filter find': {
wrapper: enhancedMatching
},
'reduceRight': {
apply: applyReduce,
slice: sliceArrayFromRight,
clamp: clampStartIndexFromRight
}
};
forEachProperty(methods, function(opts, key) {
forEach(spaceSplit(key), function(baseName) {
var methodName = baseName + 'FromIndex';
var fn = createFromIndexWithOptions(baseName, opts);
defineInstanceWithArguments(sugarArray, methodName, fn);
});
});
function forEachAsNative(fn) {
forEach(this, fn);
}
// Methods like filter and find have a direct association between the value
// returned by the callback and the element of the current iteration. This
// means that when looping, array elements must match the actual index for
// which they are being called, so the array must be sliced. This is not the
// case for methods like forEach and map, which either do not use return
// values or use them in a way that simply getting the element at a shifted
// index will not affect the final return value. However, these methods will
// still fail on sparse arrays, so always slicing them here. For example, if
// "forEachFromIndex" were to be called on [1,,2] from index 1, although the
// actual index 1 would itself would be skipped, when the array loops back to
// index 0, shifting it by adding 1 would result in the element for that
// iteration being undefined. For shifting to work, all gaps in the array
// between the actual index and the shifted index would have to be accounted
// for. This is infeasible and is easily solved by simply slicing the actual
// array instead so that gaps align. Note also that in the case of forEach,
// we are using the internal function which handles sparse arrays in a way
// that does not increment the index, and so is highly optimized compared to
// the others here, which are simply going through the native implementation.
function sliceArrayFromLeft(arr, startIndex, loop) {
var result = arr;
if (startIndex) {
result = arr.slice(startIndex);
if (loop) {
result = result.concat(arr.slice(0, startIndex));
}
}
return result;
}
// When iterating from the right, indexes are effectively shifted by 1.
// For example, iterating from the right from index 2 in an array of 3
// should also include the last element in the array. This matches the
// "lastIndexOf" method which also iterates from the right.
function sliceArrayFromRight(arr, startIndex, loop) {
if (!loop) {
startIndex += 1;
arr = arr.slice(0, max(0, startIndex));
}
return arr;
}
function clampStartIndex(startIndex, len) {
return min(len, max(0, startIndex));
}
// As indexes are shifted by 1 when starting from the right, clamping has to
// go down to -1 to accommodate the full range of the sliced array.
function clampStartIndexFromRight(startIndex, len) {
return min(len, max(-1, startIndex));
}
function applyReduce(arr, startIndex, fn, context, len, loop) {
return function(acc, val, i) {
i = getNormalizedIndex(i + startIndex, len, loop);
return fn.call(arr, acc, val, i, arr);
};
}
function applyEach(arr, startIndex, fn, context, len, loop) {
return function(el, i) {
i = getNormalizedIndex(i + startIndex, len, loop);
return fn.call(context, arr[i], i, arr);
};
}
function indexResult(result, startIndex, len) {
if (result !== -1) {
result = (result + startIndex) % len;
}
return result;
}
function createFromIndexWithOptions(methodName, opts) {
var baseFn = opts.base || Array.prototype[methodName],
applyCallback = opts.apply || applyEach,
sliceArray = opts.slice || sliceArrayFromLeft,
clampIndex = opts.clamp || clampStartIndex,
getResult = opts.result,
wrapper = opts.wrapper;
return function(arr, startIndex, args) {
var callArgs = [], argIndex = 0, lastArg, result, len, loop, fn;
len = arr.length;
if (isBoolean(args[0])) {
loop = args[argIndex++];
}
fn = args[argIndex++];
lastArg = args[argIndex];
if (startIndex < 0) {
startIndex += len;
}
startIndex = clampIndex(startIndex, len);
assertArgument(args.length);
fn = wrapper ? wrapper(fn, lastArg) : fn;
callArgs.push(applyCallback(arr, startIndex, fn, lastArg, len, loop));
if (lastArg) {
callArgs.push(lastArg);
}
result = baseFn.apply(sliceArray(arr, startIndex, loop), callArgs);
if (getResult) {
result = getResult(result, startIndex, len);
}
return result;
};
}
}
defineInstance(sugarArray, {
/***
* @method map(map, [context])
* @returns New Array
* @polyfill ES5
* @short Maps the array to another array whose elements are the values
* returned by `map`.
* @extra [context] is the `this` object. Sugar enhances this method to accept
* a string for `map`, which is a shortcut for a function that gets
* a property or invokes a function on each element.
* Supports `deep properties`.
*
* @callback mapFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3].map(function(n) {
* return n * 3;
* }); -> [3,6,9]
*
* ['a','aa','aaa'].map('length') -> [1,2,3]
* ['A','B','C'].map('toLowerCase') -> ['a','b','c']
* users.map('name') -> array of user names
*
* @param {string|mapFn} map
* @param {any} context
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {NewArrayElement} mapFn
*
***/
'map': fixArgumentLength(enhancedMap),
/***
* @method some(search, [context])
* @returns Boolean
* @polyfill ES5
* @short Returns true if `search` is true for any element in the array.
* @extra `search` can be an array element or a function of type `searchFn`.
* [context] is the `this` object. Implements `enhanced matching`.
*
* @callback searchFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @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
* users.some({ name: /^H/ }) -> true if any have a name starting with H
*
* @param {ArrayElement|searchFn} search
* @param {any} context
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {boolean} searchFn
*
***/
'some': fixArgumentLength(enhancedSome),
/***
* @method every(search, [context])
* @returns Boolean
* @polyfill ES5
* @short Returns true if `search` is true for all elements of the array.
* @extra `search` can be an array element or a function of type `searchFn`.
* [context] is the `this` object. Implements `enhanced matching`.
*
* @callback searchFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* ['a','a','a'].every(function(n) {
* return n == 'a';
* });
* ['a','a','a'].every('a') -> true
* [{a:2},{a:2}].every({a:2}) -> true
* users.every({ name: /^H/ }) -> true if all have a name starting with H
*
* @param {ArrayElement|searchFn} search
* @param {any} context
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {boolean} searchFn
*
***/
'every': fixArgumentLength(enhancedEvery),
/***
* @method filter(search, [context])
* @returns Array
* @polyfill ES5
* @short Returns any elements in the array that match `search`.
* @extra `search` can be an array element or a function of type `searchFn`.
* [context] is the `this` object. Implements `enhanced matching`.
*
* @callback searchFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3].filter(function(n) {
* return n > 1;
* });
* [1,2,2,4].filter(2) -> 2
* users.filter({ name: /^H/ }) -> all users with a name starting with H
*
* @param {ArrayElement|searchFn} search
* @param {any} context
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {boolean} searchFn
*
***/
'filter': fixArgumentLength(enhancedFilter),
/***
* @method find(search, [context])
* @returns Mixed
* @polyfill ES6
* @short Returns the first element in the array that matches `search`.
* @extra `search` can be an array element or a function of type `searchFn`.
* Implements `enhanced matching`.
*
* @callback searchFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* users.find(function(user) {
* return user.name === 'Harry';
* }); -> harry!
*
* users.find({ name: 'Harry' }); -> harry!
* users.find({ name: /^[A-H]/ }); -> First user with name starting with A-H
* users.find({ titles: ['Ms', 'Dr'] }); -> not harry!
*
* @param {ArrayElement|searchFn} search
* @param {any} context
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {boolean} searchFn
*
***/
'find': fixArgumentLength(enhancedFind),
/***
* @method findIndex(search, [context])
* @returns Number
* @polyfill ES6
* @short Returns the index of the first element in the array that matches
* `search`, or `-1` if none.
* @extra `search` can be an array element or a function of type `searchFn`.
* [context] is the `this` object. Implements `enhanced matching`.
*
* @callback searchFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3,4].findIndex(function(n) {
* return n % 2 == 0;
* }); -> 1
* ['a','b','c'].findIndex('c'); -> 2
* ['cuba','japan','canada'].find(/^c/) -> 0
*
* @param {ArrayElement|searchFn} search
* @param {any} context
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {boolean} searchFn
*
***/
'findIndex': fixArgumentLength(enhancedFindIndex)
}, [ENHANCEMENTS_FLAG, ARRAY_ENHANCEMENTS_FLAG]);
defineInstance(sugarArray, {
/***
* @method none(search, [context])
*
* @returns Boolean
* @short Returns true if none of the elements in the array match `search`.
* @extra `search` can be an array element or a function of type `searchFn`.
* [context] is the `this` object. Implements `enhanced matching`.
*
* @callback searchFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3].none(5) -> true
* ['a','b','c'].none(/b/) -> false
* users.none(function(user) {
* return user.name == 'Wolverine';
* }); -> probably true
* users.none({ name: 'Wolverine' }); -> same as above
*
* @param {ArrayElement|searchFn} search
* @param {any} context
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {boolean} searchFn
*
***/
'none': fixArgumentLength(arrayNone),
/***
* @method count(search, [context])
* @returns Number
* @short Counts all elements in the array that match `search`.
* @extra `search` can be an element or a function of type `searchFn`.
* Implements `enhanced matching`.
*
* @callback searchFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* ['a','b','a'].count('a') -> 2
* ['a','b','c'].count(/b/) -> 1
* users.count(function(user) {
* return user.age > 30;
* }); -> number of users older than 30
*
* @param {ArrayElement|searchFn} search
* @param {any} context
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {boolean} searchFn
*
***/
'count': fixArgumentLength(arrayCount),
/***
* @method min([all] = false, [map])
* @returns Mixed
* @short Returns the element in the array with the lowest value.
* @extra [map] can be passed in place of [all], and is a function of type
* `mapFn` that maps the value to be checked or a string acting as a
* shortcut. If [all] is true, multiple elements will be returned.
* Supports `deep properties`.
*
* @callback mapFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3].min() -> 1
* ['fee','fo','fum'].min('length') -> 'fo'
* ['fee','fo','fum'].min(true, 'length') -> ['fo']
* users.min('age') -> youngest guy!
*
* ['fee','fo','fum'].min(true, function(n) {
* return n.length;
* }); -> ['fo']
*
* @signature min([map])
* @param {string|mapFn} map
* @param {boolean} all
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {NewArrayElement} mapFn
*
***/
'min': function(arr, all, map) {
return getMinOrMax(arr, all, map);
},
/***
* @method max([all] = false, [map])
* @returns Mixed
* @short Returns the element in the array with the greatest value.
* @extra [map] can be passed in place of [all], and is a function of type
* `mapFn` that maps the value to be checked or a string acting as a
* shortcut. If [all] is true, multiple elements will be returned.
* Supports `deep properties`.
*
* @callback mapFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3].max() -> 3
* ['fee','fo','fum'].max('length') -> 'fee'
* ['fee','fo','fum'].max(true, 'length') -> ['fee','fum']
* users.max('age') -> oldest guy!
*
* ['fee','fo','fum'].max(true, function(n) {
* return n.length;
* }); -> ['fee', 'fum']
*
* @signature max([map])
* @param {string|mapFn} map
* @param {boolean} all
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {NewArrayElement} mapFn
*
***/
'max': function(arr, all, map) {
return getMinOrMax(arr, all, map, true);
},
/***
* @method least([all] = false, [map])
* @returns Array
* @short Returns the elements in the array with the least commonly occuring value.
* @extra [map] can be passed in place of [all], and is a function of type
* `mapFn` that maps the value to be checked or a string acting as a
* shortcut. If [all] is true, will return multiple values in an array.
* Supports `deep properties`.
*
* @callback mapFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [3,2,2].least() -> 3
* ['fe','fo','fum'].least(true, 'length') -> ['fum']
* users.least('profile.type') -> (user with least commonly occurring type)
* users.least(true, 'profile.type') -> (users with least commonly occurring type)
*
* @signature least([map])
* @param {string|mapFn} map
* @param {boolean} all
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {NewArrayElement} mapFn
*
***/
'least': function(arr, all, map) {
return getLeastOrMost(arr, all, map);
},
/***
* @method most([all] = false, [map])
* @returns Array
* @short Returns the elements in the array with the most commonly occuring value.
* @extra [map] can be passed in place of [all], and is a function of type
* `mapFn` that maps the value to be checked or a string acting as a
* shortcut. If [all] is true, will return multiple values in an array.
* Supports `deep properties`.
*
* @callback mapFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [3,2,2].most(2) -> 2
* ['fe','fo','fum'].most(true, 'length') -> ['fe','fo']
* users.most('profile.type') -> (user with most commonly occurring type)
* users.most(true, 'profile.type') -> (users with most commonly occurring type)
*
* @signature most([map])
* @param {string|mapFn} map
* @param {boolean} all
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {NewArrayElement} mapFn
*
***/
'most': function(arr, all, map) {
return getLeastOrMost(arr, all, map, true);
},
/***
* @method sum([map])
* @returns Number
* @short Sums all values in the array.
* @extra [map] can be a function of type `mapFn` that maps the value to be
* summed or a string acting as a shortcut.
*
* @callback mapFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,2].sum() -> 5
* users.sum(function(user) {
* return user.votes;
* }); -> total votes!
* users.sum('votes') -> total votes!
*
* @param {string|mapFn} map
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {NewArrayElement} mapFn
*
***/
'sum': function(arr, map) {
return sum(arr, map);
},
/***
* @method average([map])
* @returns Number
* @short Gets the mean average for all values in the array.
* @extra [map] can be a function of type `mapFn` that maps the value to be
* averaged or a string acting as a shortcut. Supports `deep properties`.
*
* @callback mapFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,3,4].average() -> 2
* users.average(function(user) {
* return user.age;
* }); -> average user age
* users.average('age') -> average user age
* users.average('currencies.usd.balance') -> average USD balance
*
* @param {string|mapFn} map
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {NewArrayElement} mapFn
*
***/
'average': function(arr, map) {
return average(arr, map);
},
/***
* @method median([map])
* @returns Number
* @short Gets the median average for all values in the array.
* @extra [map] can be a function of type `mapFn` that maps the value to be
* averaged or a string acting as a shortcut.
*
* @callback mapFn
*
* el The element of the current iteration.
* i The index of the current iteration.
* arr A reference to the array.
*
* @example
*
* [1,2,2].median() -> 2
* [{a:1},{a:2},{a:2}].median('a') -> 2
* users.median('age') -> median user age
* users.median('currencies.usd.balance') -> median USD balance
*
* @param {string|mapFn} map
* @callbackParam {ArrayElement} el
* @callbackParam {number} i
* @callbackParam {Array} arr
* @callbackReturns {NewArrayElement} mapFn
*
***/
'median': function(arr, map) {
return median(arr, map);
}
});
/*** @namespace Object ***/
// Object matchers
var objectSome = wrapObjectMatcher('some'),
objectFind = wrapObjectMatcher('find'),
objectEvery = wrapObjectMatcher('every');
function objectForEach(obj, fn) {
assertCallable(fn);
forEachProperty(obj, function(val, key) {
fn(val, key, obj);
});
return obj;
}
function objectMap(obj, map) {
var result = {};
forEachProperty(obj, function(val, key) {
result[key] = mapWithShortcuts(val, map, obj, [val, key, obj]);
});
return result;
}
function objectReduce(obj, fn, acc) {
var init = isDefined(acc);
forEachProperty(obj, function(val, key) {
if (!init) {
acc = val;
init = true;
return;
}
acc = fn(acc, val, key, obj);
});
return acc;
}
function objectNone(obj, f) {
return !objectSome(obj, f);
}
function objectFilter(obj, f) {
var matcher = getMatcher(f), result = {};
forEachProperty(obj, function(val, key) {
if (matcher(val, key, obj)) {
result[key] = val;
}
});
return result;
}
function objectCount(obj, f) {
var matcher = getMatcher(f), count = 0;
forEachProperty(obj, function(val, key) {
if (matcher(val, key, obj)) {
count++;
}
});
return count;
}
// Support
function wrapObjectMatcher(name) {
var nativeFn = Array.prototype[name];
return function(obj, f) {
var matcher = getMatcher(f);
return nativeFn.call(getKeys(obj), function(key) {
return matcher(obj[key], key, obj);
});
};
}
defineInstanceAndStatic(sugarObject, {
/***
* @method forEach(eachFn)
* @returns Object
* @short Runs `eachFn` against each property in the object.
* @extra Does not iterate over inherited or non-enumerable properties.
*
* @callback eachFn
*
* val The value of the current iteration.
* key The key of the current iteration.
* obj A reference to the object.
*
* @example
*
* Object.forEach({a:'b'}, function(val, key) {
* // val = 'b', key = a
* });
*
* @param {eachFn} eachFn
* @callbackParam {Property} val
* @callbackParam {string} key
* @callbackParam {Object} obj
*
***/
'forEach': function(obj, eachFn) {