forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lodash.js
2793 lines (2616 loc) · 83.1 KB
/
lodash.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
/*!
* Lo-Dash v0.1.0 <https://github.com/bestiejs/lodash>
* Copyright 2012 John-David Dalton <http://allyoucanleet.com/>
* Based on Underscore.js 1.3.3, copyright 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
* <http://documentcloud.github.com/underscore>
* Available under MIT license <http://mths.be/mit>
*/
;(function(window, undefined) {
'use strict';
/** Used to escape and unescape characters in templates */
var escapes = {
'\\': '\\',
"'": "'",
'r': '\r',
'n': '\n',
't': '\t',
'u2028': '\u2028',
'u2029': '\u2029'
};
// assign the result as keys and the keys as values
(function() {
for (var prop in escapes) {
escapes[escapes[prop]] = prop;
}
}());
/** Detect free variable `exports` */
var freeExports = typeof exports == 'object' && exports &&
(typeof global == 'object' && global && global == global.global && (window = global), exports);
/** Used to generate unique IDs */
var idCounter = 0;
/** Used to restore the original `_` reference in `noConflict` */
var oldDash = window._;
/** Used to replace unescape characters with their escaped counterpart */
var reEscaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
/**
* Used for `templateSettings` properties such as `escape`, `evaluate`,
* or `interpolate` with explicitly assigned falsey values to ensure no match
* is made.
*/
var reNoMatch = /.^/;
/** Used to replace escaped characters with their unescaped counterpart */
var reUnescaper = /\\(\\|'|r|n|t|u2028|u2029)/g;
/** Object#toString result shortcuts */
var arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
funcClass = '[object Function]',
numberClass = '[object Number]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
/** Native prototype shortcuts */
var ArrayProto = Array.prototype,
ObjProto = Object.prototype;
/** Native method shortcuts */
var concat = ArrayProto.concat,
hasOwnProperty = ObjProto.hasOwnProperty,
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
unshift = ArrayProto.unshift;
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeIsArray = Array.isArray,
nativeIsFinite = window.isFinite,
nativeKeys = Object.keys;
/** Timer shortcuts */
var clearInteval = window.clearInterval,
setTimeout = window.setTimeout;
/** Compilation options for `_.difference` */
var differenceFactoryOptions = {
'args': 'array',
'top': 'var values=concat.apply([],slice.call(arguments,1))',
'init': '[]',
'inLoop': 'if(indexOf(values,array[index])<0)result.push(array[index])'
};
/** Compilation options for `_.every` */
var everyFactoryOptions = {
'init': 'true',
'inLoop': 'if(!callback(collection[index],index,collection))return !result'
};
/** Compilation options for `_.extend` */
var extendFactoryOptions = {
'args': 'object',
'init': 'object',
'beforeLoop': 'for(var source,j=1,length=arguments.length;j<length;j++){\nsource=arguments[j]',
'loopExp': 'index in source',
'inLoop': 'object[index]=source[index]',
'useHas': false,
'afterLoop': '}'
};
/** Compilation options for `_.filter` */
var filterFactoryOptions = {
'init': '[]',
'inLoop': 'callback(collection[index],index,collection)&&result.push(collection[index])'
};
/** Compilation options for `_.forEach` */
var forEachFactoryOptions = {
'args': 'collection,callback,thisArg',
'top':
'if(!callback){\ncallback=identity\n}\n' +
'else if(thisArg){\ncallback=bind(callback,thisArg)\n}',
'init': 'collection',
'inLoop': 'callback(collection[index],index,collection)'
};
/** Compilation options for `_.keys` */
var keysFactoryOptions = {
'args': 'object',
'top': 'if(object!==Object(object))throw TypeError()',
'init': '[]',
'inLoop': 'result.push(index)'
};
/** Compilation options for `_.map` */
var mapFactoryOptions = {
'init': '',
'exits': '[]',
'beforeLoop': {
'array': 'result=Array(length)',
'object': 'result=[]'
},
'inLoop': {
'array': 'result[index]=callback(collection[index],index,collection)',
'object': 'result[result.length]=callback(collection[index],index,collection)'
}
};
/** Compilation options for `_.max` */
var maxFactoryOptions = {
'top':
'var current,result=-Infinity,computed=result;\n' +
'if(!callback){\n' +
'if(isArray(collection)&&collection[0]===+collection[0])return Math.max.apply(Math,collection);\n' +
'if(isEmpty(collection))return result;\n' +
'}else if(thisArg)callback=bind(callback,thisArg)',
'inLoop':
'current=callback?callback(collection[index],index,collection):collection[index];\n' +
'if(current>=computed)computed=current,result=collection[index]'
};
/*--------------------------------------------------------------------------*/
/**
* The `lodash` function.
*
* @name _
* @param {Mixed} value The value to wrap in a `Lodash` instance.
* @returns {Object} Returns a `Lodash` instance.
*/
function lodash(value) {
// allow invoking `lodash` without the `new` operator
return new Lodash(value);
}
/**
* Creates a `Lodash` instance that wraps a value to allow chaining.
*
* @private
* @constructor
* @param {Mixed} value The value to wrap.
*/
function Lodash(value) {
this._wrapped = value;
}
/*--------------------------------------------------------------------------*/
/**
* Checks if a `value` is an array.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is an array, else `false`.
* @example
*
* (function() { return _.isArray(arguments); })();
* // => false
*
* _.isArray([1, 2, 3]);
* // => true
*/
var isArray = nativeIsArray || function isArray(value) {
return toString.call(value) == arrayClass;
};
/**
* Checks if a `value` is empty. Arrays or strings with a length of 0 and
* objects with no enumerable own properties are considered "empty".
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({});
* // => true
*/
var isEmpty = iterationFactory({
'args': 'value',
'iterate': 'objects',
'top': 'var className=toString.call(value)',
'init': 'true',
'beforeLoop': 'if(className==arrayClass||className==stringClass)return !value.length',
'inLoop': 'return false'
});
/*--------------------------------------------------------------------------*/
/**
* Compiles iteration functions.
*
* @private
* @param {Object} [options1, options2, ..] The compile options objects.
* @returns {Function} Returns the compiled function.
*/
function iterationFactory() {
var prop,
index = -1,
array = {},
object = {},
options = {},
props = ['beforeLoop', 'loopExp', 'inLoop', 'afterLoop'];
while (++index < arguments.length) {
for (prop in arguments[index]) {
options[prop] = arguments[index][prop];
}
}
while ((prop = props.pop())) {
if (typeof options[prop] == 'object') {
array[prop] = options[prop].array;
object[prop] = options[prop].object;
} else {
array[prop] = object[prop] = options[prop] || '';
}
}
var args = options.args,
firstArg = /^[^,]+/.exec(args)[0],
init = options.init,
iterate = options.iterate,
arrayBranch = !(args == 'object' || iterate == 'objects'),
objectBranch = !(args == 'array' || iterate == 'arrays'),
useHas = options.useHas !== false;
return Function('arrayClass,bind,concat,funcClass,hasOwnProperty,identity,' +
'indexOf,Infinity,isArray,isEmpty,Math,slice,stringClass,' +
'toString,undefined',
'"use strict";' +
'return function(' + args + '){\n' +
(options.top || '') + ';\n' +
('var index, result' + (init ? '=' + init : '')) + ';\n' +
'if(' + firstArg + '==undefined)return ' + (options.exits || 'result') + ';\n' +
(arrayBranch
? 'var length=' + firstArg + '.length;\nindex=-1;\n' +
((objectBranch ? 'if(length===+length){\n' : '') +
(array.beforeLoop || '') + ';\n' +
'while(' + (array.loopExp || '++index<length') + '){\n' + array.inLoop + '\n}' +
(array.afterLoop || '') + ';\n' +
(objectBranch ? '\n}\n' : ''))
: ''
) +
(objectBranch
? ((arrayBranch ? 'else{\n' : '') +
(object.beforeLoop || '') + ';\n' +
'for(' + (object.loopExp || 'index in ' + firstArg) + '){\n' +
(useHas ? 'if(hasOwnProperty.call(' + /\S+$/.exec(object.loopExp || firstArg)[0] + ',index)){\n' : '') +
object.inLoop +
(useHas ? '\n}' : '') +
'\n}' +
(object.afterLoop || '') + ';\n' +
(arrayBranch ? '\n}\n' : ''))
: ''
) +
(options.bottom || '') + ';\n' +
'return ' + (options.returns || 'result') +
'\n}'
)(arrayClass, bind, concat, funcClass, hasOwnProperty, identity,
indexOf, Infinity, isArray, isEmpty, Math, slice, stringClass, toString);
}
/**
* Unescapes characters, previously escaped for inclusion in compiled string
* literals, so they may compiled into function bodies.
* (Used for template interpolation, evaluation, or escaping)
*
* @private
* @param {String} string The string to unescape.
* @returns {String} Returns the unescaped string.
*/
function unescape(string) {
return string.replace(reUnescaper, function(match, escaped) {
return escapes[escaped];
});
}
/*--------------------------------------------------------------------------*/
/**
* Checks if a given `target` value is present in a `collection` using strict
* equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @alias include
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Mixed} target The value to check for.
* @returns {Boolean} Returns `true` if `target` value is found, else `false`.
* @example
*
* _.contains([1, 2, 3], 3);
* // => true
*/
var contains = iterationFactory({
'args': 'collection,target',
'init': 'false',
'inLoop': 'if(collection[index]===target)return true'
});
/**
* Checks if the `callback` returns truthy for **all** values of a `collection`.
* The `callback` is invoked with 3 arguments; for arrays they are
* (value, index, array) and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias all
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Boolean} Returns `true` if all values pass the callback check, else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* => false
*/
var every = iterationFactory(forEachFactoryOptions, everyFactoryOptions);
/**
* Examines each value in a `collection`, returning an array of all values the
* `callback` returns truthy for. The `callback` is invoked with 3 arguments;
* for arrays they are (value, index, array) and for objects they are
* (value, key, object).
*
* @static
* @memberOf _
* @alias select
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values that passed callback check.
* @example
*
* var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [2, 4, 6]
*/
var filter = iterationFactory(forEachFactoryOptions, filterFactoryOptions);
/**
* Examines each value in a `collection`, returning the first one the `callback`
* returns truthy for. The function returns as soon as it finds an acceptable
* value, and does not iterate over the entire `collection`. The `callback` is
* invoked with 3 arguments; for arrays they are (value, index, array) and for
* objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias detect
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the value that passed the callback check, else `undefined`.
* @example
*
* var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => 2
*/
var find = iterationFactory(forEachFactoryOptions, {
'inLoop': 'if(callback(collection[index],index,collection))return collection[index]'
});
/**
* Iterates over a `collection`, executing the `callback` for each value in the
* `collection`. The `callback` is bound to the `thisArg` value, if one is passed.
* The `callback` is invoked with 3 arguments; for arrays they are
* (value, index, array) and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias each
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array|Object} Returns the `collection`.
* @example
*
* _.forEach([1, 2, 3], function(num) { alert(num); });
* // => alerts each number in turn...
*
* _.forEach({ 'one': 1, 'two': 2, 'three': 3}, function(num) { alert(num); });
* // => alerts each number in turn...
*/
var forEach = iterationFactory(forEachFactoryOptions);
/**
* Splits a `collection` into sets, grouped by the result of running each value
* through `callback`. The `callback` is invoked with 3 arguments; for arrays
* they are (value, index, array) and for objects they are (value, key, object).
* The `callback` argument may also be the name of a property to group by.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function|String} callback The function called per iteration or
* property name to group by.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Object} Returns an object of grouped values.
* @example
*
* _.groupBy([1.3, 2.1, 2.4], function(num) { return Math.floor(num); });
* // => { '1': [1.3], '2': [2.1, 2.4] }
*
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
function groupBy(collection, callback, thisArg) {
var result = {};
if (!isFunction(callback)) {
var prop = callback;
callback = function(collection) { return collection[prop]; };
}
forEach(collection, function(value, index, collection) {
var prop = callback(value, index, collection);
(result[prop] || (result[prop] = [])).push(value);
});
return result;
}
/**
* Calls the method named by `methodName` for each value of the `collection`.
* Additional arguments will be passed to each invoked method.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {String} methodName The name of the method to invoke.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
* @returns {Array} Returns a new array of values returned from each invoked method.
* @example
*
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*/
function invoke(collection, methodName) {
var args = slice.call(arguments, 2),
isFunc = isFunction(methodName);
return map(collection, function(value) {
return (isFunc ? methodName || value : value[methodName]).apply(value, args);
});
}
/**
* Produces a new array of values by mapping each value in the `collection`
* through a transformation `callback`. The `callback` is bound to the `thisArg`
* value, if one is passed. The `callback` is invoked with 3 arguments; for
* arrays they are (value, index, array) and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values returned by the callback.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9]
*/
var map = iterationFactory(forEachFactoryOptions, mapFactoryOptions);
/**
* Retrieves the maximum value of a `collection`. If `callback` is passed,
* it will be executed for each value in the `collection` to generate the
* criterion by which the value is ranked. The `callback` is invoked with 3
* arguments; for arrays they are (value, index, array) and for objects they
* are (value, key, object).
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [callback] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the maximum value.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 },
* { 'name': 'curly', 'age': 60 }
* ];
*
* _.max(stooges, function(stooge) { return stooge.age; });
* // => { 'name': 'curly', 'age': 60 };
*/
var max = iterationFactory(forEachFactoryOptions, maxFactoryOptions);
/**
* Retrieves the minimum value of a `collection`. If `callback` is passed,
* it will be executed for each value in the `collection` to generate the
* criterion by which the value is ranked. The `callback` is invoked with 3
* arguments; for arrays they are (value, index, array) and for objects they
* are (value, key, object).
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [callback] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the minimum value.
* @example
*
* _.min([10, 5, 100, 2, 1000]);
* // => 2
*/
var min = iterationFactory(forEachFactoryOptions, maxFactoryOptions, {
'top': maxFactoryOptions.top.replace('-', '').replace('max', 'min'),
'inLoop': maxFactoryOptions.inLoop.replace('>=', '<')
});
/**
* Retrieves the value of a specified property from all values in a `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {String} property The property to pluck.
* @returns {Array} Returns a new array of property values.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 },
* { 'name': 'curly', 'age': 60 }
* ];
*
* _.pluck(stooges, 'name');
* // => ['moe', 'larry', 'curly']
*/
var pluck = iterationFactory(mapFactoryOptions, {
'args': 'collection,property',
'inLoop': {
'array': 'result[index]=collection[index][property]',
'object': 'result[result.length]=collection[index][property]'
}
});
/**
* Boils down a `collection` to a single value. The initial state of the
* reduction is `accumulator` and each successive step of it should be returned
* by the `callback`. The `callback` is bound to the `thisArg` value, if one is
* passed. The `callback` is invoked with 4 arguments; for arrays they are
* (accumulator, value, index, array) and for objects they are
* (accumulator, value, key, object).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [accumulator] Initial value of the accumulator.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; });
* // => 6
*/
var reduce = iterationFactory({
'args':
'collection,callback,accumulator,thisArg',
'top':
'var initial=arguments.length>2;\n' +
'if(thisArg)callback=bind(callback,thisArg)',
'init':
'accumulator',
'beforeLoop': {
'array': 'if(!initial)result=collection[++index]'
},
'inLoop': {
'array':
'result=callback(result,collection[index],index,collection)',
'object':
'result=initial\n' +
'?callback(result,collection[index],index,collection)\n' +
':(initial=true,collection[index])'
}
});
/**
* The right-associative version of `_.reduce`. The `callback` is bound to the
* `thisArg` value, if one is passed. The `callback` is invoked with 4 arguments;
* for arrays they are (accumulator, value, index, array) and for objects they
* are (accumulator, value, key, object).
*
* @static
* @memberOf _
* @alias foldr
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [accumulator] Initial value of the accumulator.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the accumulated value.
* @example
*
* var list = [[0, 1], [2, 3], [4, 5]];
* var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, callback, result, thisArg) {
var initial = arguments.length > 2;
if (collection == undefined) {
return result;
}
if(thisArg) {
callback = bind(callback, thisArg);
}
var length = collection.length;
if (length === +length) {
if (length && !initial) {
result = collection[--length];
}
while (length--) {
result = callback(result, collection[length], length, collection);
}
return result;
}
var prop,
props = keys(collection);
length = props.length;
if (length && !initial) {
result = collection[props[--length]];
}
while (length--) {
prop = props[length];
result = callback(result, collection[prop], prop, collection);
}
return result;
}
/**
* The opposite of `_.filter`, this method returns the values of a `collection`
* that `callback` does **not** return truthy for. The `callback` is invoked
* with 3 arguments; for arrays they are (value, index, array) and for objects
* they are (value, key, object).
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values that did **not** pass the callback check.
* @example
*
* var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [1, 3, 5]
*/
var reject = iterationFactory(forEachFactoryOptions, filterFactoryOptions, {
'inLoop': '!' + filterFactoryOptions.inLoop
});
/**
* Produces a new array of shuffled `collection` values, using a version of the
* Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns a new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(collection) {
var rand,
result = [];
forEach(collection, function(value, index) {
rand = Math.floor(Math.random() * (index + 1));
result[index] = result[rand];
result[rand] = value;
});
return result;
}
/**
* Gets the number of values in the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection inspect.
* @returns {Number} Returns the number of values in the collection.
* @example
*
* _.size({ 'one': 1, 'two': 2, 'three': 3 });
* // => 3
*/
function size(collection) {
var className = toString.call(collection);
return className == arrayClass || className == stringClass
? collection.length
: keys(collection).length;
}
/**
* Produces a new sorted array, ranked in ascending order by the results of
* running each value of a `collection` through `callback`. The `callback` is
* invoked with 3 arguments; for arrays they are (value, index, array) and for
* objects they are (value, key, object). The `callback` argument may also be
* the name of a property to sort by (e.g. 'length').
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function|String} callback The function called per iteration or
* property name to sort by.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of sorted values.
* @example
*
* _.sortBy([1, 2, 3, 4, 5, 6], function(num) { return Math.sin(num); });
* // => [5, 4, 6, 3, 1, 2]
*/
function sortBy(collection, callback, thisArg) {
if (!isFunction(callback)) {
var prop = callback;
callback = function(collection) { return collection[prop]; };
} else if (thisArg) {
callback = bind(callback, thisArg);
}
return pluck(map(collection, function(value, index) {
return {
'criteria': callback(value, index, collection),
'value': value
};
}).sort(function(left, right) {
var a = left.criteria,
b = right.criteria;
if (a === undefined) {
return 1;
}
if (b === undefined) {
return -1;
}
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
}
/**
* Checks if the `callback` returns truthy for **any** value of a `collection`.
* The function returns as soon as it finds passing value, and does not iterate
* over the entire `collection`. The `callback` is invoked with 3 arguments; for
* arrays they are (value, index, array) and for objects they are
* (value, key, object).
*
* @static
* @memberOf _
* @alias any
* @category Collections
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Boolean} Returns `true` if any value passes the callback check, else `false`.
* @example
*
* _.some([null, 0, 'yes', false]);
* // => true
*/
var some = iterationFactory(forEachFactoryOptions, everyFactoryOptions, {
'init': 'false',
'inLoop': everyFactoryOptions.inLoop.replace('!', '')
});
/**
* Uses a binary search to determine the smallest index at which the `value`
* should be inserted into the `collection` in order to maintain the sort order
* of the `collection`. If `callback` is passed, it will be executed for each
* value in the `collection` to compute their sort ranking. The `callback` is
* invoked with 1 argument.
*
* @static
* @memberOf _
* @category Collections
* @param {Array} array The array to iterate over.
* @param {Mixed} value The value to evaluate.
* @param {Function} [callback] The function called per iteration.
* @returns {Number} Returns the index at which the value should be inserted
* into the collection.
* @example
*
* _.sortedIndex([10, 20, 30, 40, 50], 35);
* // => 3
*/
function sortedIndex(array, object, callback) {
var low = 0,
high = array.length;
callback || (callback = identity);
while (low < high) {
var mid = (low + high) >> 1;
callback(array[mid]) < callback(object) ? (low = mid + 1) : (high = mid);
}
return low;
}
/**
* Converts the `collection`, into an array. Useful for converting the
* `arguments` object.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to convert.
* @returns {Array} Returns the new converted array.
* @example
*
* (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
* // => [2, 3, 4]
*/
function toArray(collection) {
if (!collection) {
return [];
}
if (isFunction(collection.toArray)) {
return collection.toArray();
}
var length = collection.length;
if (length === +length) {
return slice.call(collection);
}
return values(collection);
}
/**
* Produces an array of enumerable own property values of the `collection`.
*
* @static
* @memberOf _
* @alias methods
* @category Collections
* @param {Array|Object} collection The collection to inspect.
* @returns {Array} Returns a new array of property values.
* @example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3]
*/
var values = iterationFactory(mapFactoryOptions, {
'args': 'collection',
'inLoop': {
'array': 'result[index]=collection[index]',
'object': 'result[result.length]=collection[index]'
}
});
/*--------------------------------------------------------------------------*/
/**
* Produces a new array with all falsey values of `array` removed. The values
* `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @returns {Array} Returns a new filtered array.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
var compact = iterationFactory({
'args': 'array',
'init': '[]',
'inLoop': 'if(array[index])result.push(array[index])'
});
/**
* Produces a new array of `array` values not present in the other arrays
* using strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @param {Mixed} [array1, array2, ...] Arrays to check.
* @returns {Array} Returns a new array of `array` values not present in the
* other arrays.
* @example
*
* _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
* // => [1, 3, 4]
*/
var difference = iterationFactory(differenceFactoryOptions);
/**
* Gets the first value of the `array`. Pass `n` to return the first `n` values
* of the `array`.
*
* @static
* @memberOf _
* @alias head, take
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Mixed} Returns the first value or an array of the first `n` values
* of the `array`.
* @example
*
* _.first([5, 4, 3, 2, 1]);
* // => 5
*/
function first(array, n, guard) {
return (n == undefined || guard) ? array[0] : slice.call(array, 0, n);
}
/**
* Flattens a nested array (the nesting can be to any depth). If `shallow` is
* truthy, `array` will only be flattened a single level.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @param {Boolean} shallow A flag to indicate only flattening a single level.
* @returns {Array} Returns a new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, [[4]]];
*/
function flatten(array, shallow) {
if (shallow) {
return concat.apply([], array);
}