-
Notifications
You must be signed in to change notification settings - Fork 15
/
lodash.js
4462 lines (4161 loc) · 137 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.7.0 <http://lodash.com>
* 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://lodash.com/license>
*/
;(function(window, undefined) {
'use strict';
/**
* Used to cache the last `_.templateSettings.evaluate` delimiter to avoid
* unnecessarily assigning `reEvaluateDelimiter` a new generated regexp.
* Assigned in `_.template`.
*/
var lastEvaluateDelimiter;
/**
* Used to cache the last template `options.variable` to avoid unnecessarily
* assigning `reDoubleVariable` a new generated regexp. Assigned in `_.template`.
*/
var lastVariable;
/**
* Used to match potentially incorrect data object references, like `obj.obj`,
* in compiled templates. Assigned in `_.template`.
*/
var reDoubleVariable;
/**
* Used to match "evaluate" delimiters, including internal delimiters,
* in template text. Assigned in `_.template`.
*/
var reEvaluateDelimiter;
/** Detect free variable `exports` */
var freeExports = typeof exports == 'object' && exports &&
(typeof global == 'object' && global && global == global.global && (window = global), exports);
/** Native prototype shortcuts */
var ArrayProto = Array.prototype,
BoolProto = Boolean.prototype,
ObjectProto = Object.prototype,
NumberProto = Number.prototype,
StringProto = String.prototype;
/** Used to generate unique IDs */
var idCounter = 0;
/** Used by `cachedContains` as the default size when optimizations are enabled for large arrays */
var largeArraySize = 30;
/** Used to restore the original `_` reference in `noConflict` */
var oldDash = window._;
/** Used to detect delimiter values that should be processed by `tokenizeEvaluate` */
var reComplexDelimiter = /[-?+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/;
/** Used to match HTML entities */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#x27);/g;
/** Used to match empty string literals in compiled template source */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match regexp flags from their coerced string values */
var reFlags = /\w*$/;
/** Used to insert the data object variable into compiled template source */
var reInsertVariable = /(?:__e|__t = )\(\s*(?![\d\s"']|this\.)/g;
/** Used to detect if a method is native */
var reNative = RegExp('^' +
(ObjectProto.valueOf + '')
.replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&')
.replace(/valueOf|for [^\]]+/g, '.+?') + '$'
);
/** Used to match internally used tokens in template text */
var reToken = /__token(\d+)__/g;
/** Used to match HTML characters */
var reUnescapedHtml = /[&<>"']/g;
/** Used to match unescaped characters in compiled string literals */
var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
/** Used to fix the JScript [[DontEnum]] bug */
var shadowed = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used to make template sourceURLs easier to identify */
var templateCounter = 0;
/** Used to replace template delimiters */
var tokenHead = '__token',
tokenFoot = '__';
/** Used to store tokenized template text snippets */
var tokenized = [];
/** Native method shortcuts */
var concat = ArrayProto.concat,
hasOwnProperty = ObjectProto.hasOwnProperty,
push = ArrayProto.push,
propertyIsEnumerable = ObjectProto.propertyIsEnumerable,
slice = ArrayProto.slice,
toString = ObjectProto.toString;
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeBind = reNative.test(nativeBind = slice.bind) && nativeBind,
nativeFloor = Math.floor,
nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
nativeIsFinite = window.isFinite,
nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys,
nativeMax = Math.max,
nativeMin = Math.min,
nativeRandom = Math.random;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
/** Timer shortcuts */
var clearTimeout = window.clearTimeout,
setTimeout = window.setTimeout;
/**
* Detect the JScript [[DontEnum]] bug:
*
* In IE < 9 an objects own properties, shadowing non-enumerable ones, are
* made non-enumerable as well.
*/
var hasDontEnumBug;
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects
* incorrectly:
*
* Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
* and `splice()` functions that fail to remove the last element, `value[0]`,
* of array-like objects even though the `length` property is set to `0`.
* The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
* is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
*/
var hasObjectSpliceBug;
/** Detect if own properties are iterated after inherited properties (IE < 9) */
var iteratesOwnLast;
/** Detect if an `arguments` object's indexes are non-enumerable (IE < 9) */
var noArgsEnum = true;
(function() {
var object = { '0': 1, 'length': 1 },
props = [];
function ctor() { this.x = 1; }
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var prop in new ctor) { props.push(prop); }
for (prop in arguments) { noArgsEnum = !prop; }
hasDontEnumBug = (props + '').length < 4;
iteratesOwnLast = props[0] != 'x';
hasObjectSpliceBug = (props.splice.call(object, 0, 1), object[0]);
}(1));
/** Detect if an `arguments` object's [[Class]] is unresolvable (Firefox < 4, IE < 9) */
var noArgsClass = !isArguments(arguments);
/** Detect if `Array#slice` cannot be used to convert strings to arrays (Opera < 10.52) */
var noArraySliceOnStrings = slice.call('x')[0] != 'x';
/**
* Detect lack of support for accessing string characters by index:
*
* IE < 8 can't access characters by index and IE 8 can only access
* characters by index on string literals.
*/
var noCharByIndex = ('x'[0] + Object('x')[0]) != 'xx';
/**
* Detect if a node's [[Class]] is unresolvable (IE < 9)
* and that the JS engine won't error when attempting to coerce an object to
* a string without a `toString` property value of `typeof` "function".
*/
try {
var noNodeClass = ({ 'toString': 0 } + '', toString.call(window.document || 0) == objectClass);
} catch(e) { }
/* Detect if `Function#bind` exists and is inferred to be fast (all but V8) */
var isBindFast = nativeBind && /\n|Opera/.test(nativeBind + toString.call(window.opera));
/* Detect if `Object.keys` exists and is inferred to be fast (IE, Opera, V8) */
var isKeysFast = nativeKeys && /^.+$|true/.test(nativeKeys + !!window.attachEvent);
/* Detect if strict mode, "use strict", is inferred to be fast (V8) */
var isStrictFast = !isBindFast;
/**
* Detect if sourceURL syntax is usable without erroring:
*
* The JS engine in Adobe products, like InDesign, will throw a syntax error
* when it encounters a single line comment beginning with the `@` symbol.
*
* The JS engine in Narwhal will generate the function `function anonymous(){//}`
* and throw a syntax error.
*
* Avoid comments beginning `@` symbols in IE because they are part of its
* non-standard conditional compilation support.
* http://msdn.microsoft.com/en-us/library/121hztk3(v=vs.94).aspx
*/
try {
var useSourceURL = (Function('//@')(), !window.attachEvent);
} catch(e) { }
/** Used to identify object classifications that are array-like */
var arrayLikeClasses = {};
arrayLikeClasses[boolClass] = arrayLikeClasses[dateClass] = arrayLikeClasses[funcClass] =
arrayLikeClasses[numberClass] = arrayLikeClasses[objectClass] = arrayLikeClasses[regexpClass] = false;
arrayLikeClasses[argsClass] = arrayLikeClasses[arrayClass] = arrayLikeClasses[stringClass] = true;
/** Used to identify object classifications that `_.clone` supports */
var cloneableClasses = {};
cloneableClasses[argsClass] = cloneableClasses[funcClass] = false;
cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] =
cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] =
cloneableClasses[stringClass] = true;
/**
* Used to convert characters to HTML entities:
*
* Though the `>` character is escaped for symmetry, characters like `>` and `/`
* don't require escaping in HTML and have no special meaning unless they're part
* of a tag or an unquoted attribute value.
* http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
*/
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to convert HTML entities to characters */
var htmlUnescapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
};
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false,
'unknown': true
};
/** Used to escape characters for inclusion in compiled string literals */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/*--------------------------------------------------------------------------*/
/**
* The `lodash` function.
*
* @name _
* @constructor
* @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) {
// exit early if already wrapped
if (value && value.__wrapped__) {
return value;
}
this.__wrapped__ = value;
}
/**
* By default, the template delimiters used by Lo-Dash are similar to those in
* embedded Ruby (ERB). Change the following template settings to use alternative
* delimiters.
*
* @static
* @memberOf _
* @type Object
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'escape': /<%-([\s\S]+?)%>/g,
/**
* Used to detect code to be evaluated.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': /<%([\s\S]+?)%>/g,
/**
* Used to detect `data` property values to inject.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'interpolate': /<%=([\s\S]+?)%>/g,
/**
* Used to reference the data object in the template text.
*
* @static
* @memberOf _.templateSettings
* @type String
*/
'variable': ''
};
/*--------------------------------------------------------------------------*/
/**
* The template used to create iterator functions.
*
* @private
* @param {Obect} data The data object used to populate the text.
* @returns {String} Returns the interpolated text.
*/
var iteratorTemplate = template(
// conditional strict mode
'<% if (useStrict) { %>\'use strict\';\n<% } %>' +
// the `iteratee` may be reassigned by the `top` snippet
'var index, value, iteratee = <%= firstArg %>, ' +
// assign the `result` variable an initial value
'result<% if (init) { %> = <%= init %><% } %>;\n' +
// add code to exit early or do so if the first argument is falsey
'<%= exit %>;\n' +
// add code after the exit snippet but before the iteration branches
'<%= top %>;\n' +
// the following branch is for iterating arrays and array-like objects
'<% if (arrayBranch) { %>' +
'var length = iteratee.length; index = -1;' +
' <% if (objectBranch) { %>\nif (length > -1 && length === length >>> 0) {<% } %>' +
// add support for accessing string characters by index if needed
' <% if (noCharByIndex) { %>\n' +
' if (toString.call(iteratee) == stringClass) {\n' +
' iteratee = iteratee.split(\'\')\n' +
' }' +
' <% } %>\n' +
' <%= arrayBranch.beforeLoop %>;\n' +
' while (++index < length) {\n' +
' value = iteratee[index];\n' +
' <%= arrayBranch.inLoop %>\n' +
' }' +
' <% if (objectBranch) { %>\n}<% } %>' +
'<% } %>' +
// the following branch is for iterating an object's own/inherited properties
'<% if (objectBranch) { %>' +
' <% if (arrayBranch) { %>\nelse {' +
// add support for iterating over `arguments` objects if needed
' <% } else if (noArgsEnum) { %>\n' +
' var length = iteratee.length; index = -1;\n' +
' if (length && isArguments(iteratee)) {\n' +
' while (++index < length) {\n' +
' value = iteratee[index += \'\'];\n' +
' <%= objectBranch.inLoop %>\n' +
' }\n' +
' } else {' +
' <% } %>' +
// Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
// (if the prototype or a property on the prototype has been set)
// incorrectly sets a function's `prototype` property [[Enumerable]]
// value to `true`. Because of this Lo-Dash standardizes on skipping
// the the `prototype` property of functions regardless of its
// [[Enumerable]] value.
' <% if (!hasDontEnumBug) { %>\n' +
' var skipProto = typeof iteratee == \'function\' && \n' +
' propertyIsEnumerable.call(iteratee, \'prototype\');\n' +
' <% } %>' +
// iterate own properties using `Object.keys` if it's fast
' <% if (isKeysFast && useHas) { %>\n' +
' var ownIndex = -1,\n' +
' ownProps = objectTypes[typeof iteratee] ? nativeKeys(iteratee) : [],\n' +
' length = ownProps.length;\n\n' +
' <%= objectBranch.beforeLoop %>;\n' +
' while (++ownIndex < length) {\n' +
' index = ownProps[ownIndex];\n' +
' <% if (!hasDontEnumBug) { %>if (!(skipProto && index == \'prototype\')) {\n <% } %>' +
' value = iteratee[index];\n' +
' <%= objectBranch.inLoop %>\n' +
' <% if (!hasDontEnumBug) { %>}\n<% } %>' +
' }' +
// else using a for-in loop
' <% } else { %>\n' +
' <%= objectBranch.beforeLoop %>;\n' +
' for (index in iteratee) {<%' +
' if (!hasDontEnumBug || useHas) { %>\n if (<%' +
' if (!hasDontEnumBug) { %>!(skipProto && index == \'prototype\')<% }' +
' if (!hasDontEnumBug && useHas) { %> && <% }' +
' if (useHas) { %>hasOwnProperty.call(iteratee, index)<% }' +
' %>) {' +
' <% } %>\n' +
' value = iteratee[index];\n' +
' <%= objectBranch.inLoop %>;\n' +
' <% if (!hasDontEnumBug || useHas) { %>}\n<% } %>' +
' }' +
' <% } %>' +
// Because IE < 9 can't set the `[[Enumerable]]` attribute of an
// existing property and the `constructor` property of a prototype
// defaults to non-enumerable, Lo-Dash skips the `constructor`
// property when it infers it's iterating over a `prototype` object.
' <% if (hasDontEnumBug) { %>\n\n' +
' var ctor = iteratee.constructor;\n' +
' <% for (var k = 0; k < 7; k++) { %>\n' +
' index = \'<%= shadowed[k] %>\';\n' +
' if (<%' +
' if (shadowed[k] == \'constructor\') {' +
' %>!(ctor && ctor.prototype === iteratee) && <%' +
' } %>hasOwnProperty.call(iteratee, index)) {\n' +
' value = iteratee[index];\n' +
' <%= objectBranch.inLoop %>\n' +
' }' +
' <% } %>' +
' <% } %>' +
' <% if (arrayBranch || noArgsEnum) { %>\n}<% } %>' +
'<% } %>\n' +
// add code to the bottom of the iteration function
'<%= bottom %>;\n' +
// finally, return the `result`
'return result'
);
/**
* Reusable iterator options shared by
* `every`, `filter`, `find`, `forEach`, `forIn`, `forOwn`, `groupBy`, `map`,
* `reject`, `some`, and `sortBy`.
*/
var baseIteratorOptions = {
'args': 'collection, callback, thisArg',
'init': 'collection',
'top':
'if (!callback) {\n' +
' callback = identity\n' +
'}\n' +
'else if (thisArg) {\n' +
' callback = iteratorBind(callback, thisArg)\n' +
'}',
'inLoop': 'if (callback(value, index, collection) === false) return result'
};
/** Reusable iterator options for `countBy`, `groupBy`, and `sortBy` */
var countByIteratorOptions = {
'init': '{}',
'top':
'var prop;\n' +
'if (typeof callback != \'function\') {\n' +
' var valueProp = callback;\n' +
' callback = function(value) { return value[valueProp] }\n' +
'}\n' +
'else if (thisArg) {\n' +
' callback = iteratorBind(callback, thisArg)\n' +
'}',
'inLoop':
'prop = callback(value, index, collection);\n' +
'(hasOwnProperty.call(result, prop) ? result[prop]++ : result[prop] = 1)'
};
/** Reusable iterator options for `every` and `some` */
var everyIteratorOptions = {
'init': 'true',
'inLoop': 'if (!callback(value, index, collection)) return !result'
};
/** Reusable iterator options for `defaults` and `extend` */
var extendIteratorOptions = {
'useHas': false,
'useStrict': false,
'args': 'object',
'init': 'object',
'top':
'for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {\n' +
' if (iteratee = arguments[argsIndex]) {',
'inLoop': 'result[index] = value',
'bottom': ' }\n}'
};
/** Reusable iterator options for `filter`, `reject`, and `where` */
var filterIteratorOptions = {
'init': '[]',
'inLoop': 'callback(value, index, collection) && result.push(value)'
};
/** Reusable iterator options for `find`, `forEach`, `forIn`, and `forOwn` */
var forEachIteratorOptions = {
'top': 'if (thisArg) callback = iteratorBind(callback, thisArg)'
};
/** Reusable iterator options for `forIn` and `forOwn` */
var forOwnIteratorOptions = {
'inLoop': {
'object': baseIteratorOptions.inLoop
}
};
/** Reusable iterator options for `invoke`, `map`, `pluck`, and `sortBy` */
var mapIteratorOptions = {
'init': '',
'exit': 'if (!collection) return []',
'beforeLoop': {
'array': 'result = Array(length)',
'object': 'result = ' + (isKeysFast ? 'Array(length)' : '[]')
},
'inLoop': {
'array': 'result[index] = callback(value, index, collection)',
'object': 'result' + (isKeysFast ? '[ownIndex] = ' : '.push') + '(callback(value, index, collection))'
}
};
/** Reusable iterator options for `omit` and `pick` */
var omitIteratorOptions = {
'useHas': false,
'args': 'object, callback, thisArg',
'init': '{}',
'top':
'var isFunc = typeof callback == \'function\';\n' +
'if (!isFunc) {\n' +
' var props = concat.apply(ArrayProto, arguments)\n' +
'} else if (thisArg) {\n' +
' callback = iteratorBind(callback, thisArg)\n' +
'}',
'inLoop':
'if (isFunc\n' +
' ? !callback(value, index, object)\n' +
' : indexOf(props, index) < 0\n' +
') result[index] = value'
};
/*--------------------------------------------------------------------------*/
/**
* Creates a new function optimized for searching large arrays for a given `value`,
* starting at `fromIndex`, using strict equality for comparisons, i.e. `===`.
*
* @private
* @param {Array} array The array to search.
* @param {Mixed} value The value to search for.
* @param {Number} [fromIndex=0] The index to start searching from.
* @param {Number} [largeSize=30] The length at which an array is considered large.
* @returns {Boolean} Returns `true` if `value` is found, else `false`.
*/
function cachedContains(array, fromIndex, largeSize) {
fromIndex || (fromIndex = 0);
var length = array.length,
isLarge = (length - fromIndex) >= (largeSize || largeArraySize),
cache = isLarge ? {} : array;
if (isLarge) {
// init value cache
var key,
index = fromIndex - 1;
while (++index < length) {
// manually coerce `value` to string because `hasOwnProperty`, in some
// older versions of Firefox, coerces objects incorrectly
key = array[index] + '';
(hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = [])).push(array[index]);
}
}
return function(value) {
if (isLarge) {
var key = value + '';
return hasOwnProperty.call(cache, key) && indexOf(cache[key], value) > -1;
}
return indexOf(cache, value, fromIndex) > -1;
}
}
/**
* Creates compiled iteration functions. The iteration function will be created
* to iterate over only objects if the first argument of `options.args` is
* "object" or `options.inLoop.array` is falsey.
*
* @private
* @param {Object} [options1, options2, ...] The compile options objects.
*
* useHas - A boolean to specify whether or not to use `hasOwnProperty` checks
* in the object loop.
*
* useStrict - A boolean to specify whether or not to include the ES5
* "use strict" directive.
*
* args - A string of comma separated arguments the iteration function will
* accept.
*
* init - A string to specify the initial value of the `result` variable.
*
* exit - A string of code to use in place of the default exit-early check
* of `if (!arguments[0]) return result`.
*
* top - A string of code to execute after the exit-early check but before
* the iteration branches.
*
* beforeLoop - A string or object containing an "array" or "object" property
* of code to execute before the array or object loops.
*
* inLoop - A string or object containing an "array" or "object" property
* of code to execute in the array or object loops.
*
* bottom - A string of code to execute after the iteration branches but
* before the `result` is returned.
*
* @returns {Function} Returns the compiled function.
*/
function createIterator() {
var object,
prop,
value,
index = -1,
length = arguments.length;
// merge options into a template data object
var data = {
'bottom': '',
'exit': '',
'init': '',
'top': '',
'arrayBranch': { 'beforeLoop': '' },
'objectBranch': { 'beforeLoop': '' }
};
while (++index < length) {
object = arguments[index];
for (prop in object) {
value = (value = object[prop]) == null ? '' : value;
// keep this regexp explicit for the build pre-process
if (/beforeLoop|inLoop/.test(prop)) {
if (typeof value == 'string') {
value = { 'array': value, 'object': value };
}
data.arrayBranch[prop] = value.array || '';
data.objectBranch[prop] = value.object || '';
} else {
data[prop] = value;
}
}
}
// set additional template `data` values
var args = data.args,
firstArg = /^[^,]+/.exec(args)[0],
useStrict = data.useStrict;
data.firstArg = firstArg;
data.hasDontEnumBug = hasDontEnumBug;
data.isKeysFast = isKeysFast;
data.noArgsEnum = noArgsEnum;
data.shadowed = shadowed;
data.useHas = data.useHas !== false;
data.useStrict = useStrict == null ? isStrictFast : useStrict;
if (data.noCharByIndex == null) {
data.noCharByIndex = noCharByIndex;
}
if (!data.exit) {
data.exit = 'if (!' + firstArg + ') return result';
}
if (firstArg != 'collection' || !data.arrayBranch.inLoop) {
data.arrayBranch = null;
}
// create the function factory
var factory = Function(
'arrayLikeClasses, ArrayProto, bind, compareAscending, concat, forIn, ' +
'hasOwnProperty, identity, indexOf, isArguments, isArray, isFunction, ' +
'isPlainObject, iteratorBind, objectClass, objectTypes, nativeKeys, ' +
'propertyIsEnumerable, slice, stringClass, toString',
'var callee = function(' + args + ') {\n' + iteratorTemplate(data) + '\n};\n' +
'return callee'
);
// return the compiled function
return factory(
arrayLikeClasses, ArrayProto, bind, compareAscending, concat, forIn,
hasOwnProperty, identity, indexOf, isArguments, isArray, isFunction,
isPlainObject, iteratorBind, objectClass, objectTypes, nativeKeys,
propertyIsEnumerable, slice, stringClass, toString
);
}
/**
* Used by `sortBy` to compare transformed `collection` values, stable sorting
* them in ascending order.
*
* @private
* @param {Object} a The object to compare to `b`.
* @param {Object} b The object to compare to `a`.
* @returns {Number} Returns the sort order indicator of `1` or `-1`.
*/
function compareAscending(a, b) {
var ai = a.index,
bi = b.index;
a = a.criteria;
b = b.criteria;
// ensure a stable sort in V8 and other engines
// http://code.google.com/p/v8/issues/detail?id=90
if (a !== b) {
if (a > b || a === undefined) {
return 1;
}
if (a < b || b === undefined) {
return -1;
}
}
return ai < bi ? -1 : 1;
}
/**
* Used by `template` to replace tokens with their corresponding code snippets.
*
* @private
* @param {String} match The matched token.
* @param {String} index The `tokenized` index of the code snippet.
* @returns {String} Returns the code snippet.
*/
function detokenize(match, index) {
return tokenized[index];
}
/**
* Used by `template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {String} match The matched character to escape.
* @returns {String} Returns the escaped character.
*/
function escapeStringChar(match) {
return '\\' + stringEscapes[match];
}
/**
* Used by `escape` to convert characters to HTML entities.
*
* @private
* @param {String} match The matched character to escape.
* @returns {String} Returns the escaped character.
*/
function escapeHtmlChar(match) {
return htmlEscapes[match];
}
/**
* Creates a new function that, when called, invokes `func` with the `this`
* binding of `thisArg` and the arguments (value, index, object).
*
* @private
* @param {Function} func The function to bind.
* @param {Mixed} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new bound function.
*/
function iteratorBind(func, thisArg) {
return function(value, index, object) {
return func.call(thisArg, value, index, object);
};
}
/**
* A no-operation function.
*
* @private
*/
function noop() {
// no operation performed
}
/**
* Used by `template` to replace "escape" template delimiters with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} value The delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeEscape(match, value) {
if (match && reComplexDelimiter.test(value)) {
return '<e%-' + value + '%>';
}
var index = tokenized.length;
tokenized[index] = "' +\n__e(" + value + ") +\n'";
return tokenHead + index + tokenFoot;
}
/**
* Used by `template` to replace "evaluate" template delimiters, or complex
* "escape" and "interpolate" delimiters, with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} escapeValue The complex "escape" delimiter value.
* @param {String} interpolateValue The complex "interpolate" delimiter value.
* @param {String} [evaluateValue] The "evaluate" delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeEvaluate(match, escapeValue, interpolateValue, evaluateValue) {
if (evaluateValue) {
var index = tokenized.length;
tokenized[index] = "';\n" + evaluateValue + ";\n__p += '";
return tokenHead + index + tokenFoot;
}
return escapeValue
? tokenizeEscape(null, escapeValue)
: tokenizeInterpolate(null, interpolateValue);
}
/**
* Used by `template` to replace "interpolate" template delimiters with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} value The delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeInterpolate(match, value) {
if (match && reComplexDelimiter.test(value)) {
return '<e%=' + value + '%>';
}
var index = tokenized.length;
tokenized[index] = "' +\n((__t = (" + value + ")) == null ? '' : __t) +\n'";
return tokenHead + index + tokenFoot;
}
/**
* Used by `unescape` to convert HTML entities to characters.
*
* @private
* @param {String} match The matched character to unescape.
* @returns {String} Returns the unescaped character.
*/
function unescapeHtmlChar(match) {
return htmlUnescapes[match];
}
/*--------------------------------------------------------------------------*/
/**
* Checks if `value` is an `arguments` object.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })(1, 2, 3);
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return toString.call(value) == argsClass;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (noArgsClass) {
isArguments = function(value) {
return !!(value && hasOwnProperty.call(value, 'callee'));
};
}
/**
* Checks if `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(value) {
return toString.call(value) == arrayClass;
};
/**
* Checks if `value` is a function.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a function, else `false`.
* @example
*
* _.isFunction(''.concat);
* // => true
*/
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return toString.call(value) == funcClass;
};
}
/**
* A fallback implementation of `isPlainObject` that checks if a given `value`
* is an object created by the `Object` constructor, assuming objects created
* by the `Object` constructor have no inherited enumerable properties and that
* there are no `Object.prototype` extensions.
*
* @private
* @param {Mixed} value The value to check.
* @param {Boolean} [skipArgsCheck=false] Internally used to skip checks for
* `arguments` objects.
* @returns {Boolean} Returns `true` if `value` is a plain object, else `false`.
*/
function isPlainFallback(value, skipArgsCheck) {
// avoid non-objects and false positives for `arguments` objects
var result = false;
if (!(value && typeof value == 'object') || (!skipArgsCheck && isArguments(value))) {
return result;
}
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings.
// Also check that the constructor is `Object` (i.e. `Object instanceof Object`)
var ctor = value.constructor;
if ((!noNodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) &&
(!isFunction(ctor) || ctor instanceof ctor)) {
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
if (iteratesOwnLast) {
forIn(value, function(value, key, object) {
result = !hasOwnProperty.call(object, key);
return false;