UNPKG

732 kBJavaScriptView Raw
1/**
2 * k2 - Functional javascript utils
3 * @version v0.8.0
4 */
5(function webpackUniversalModuleDefinition(root, factory) {
6 if(typeof exports === 'object' && typeof module === 'object')
7 module.exports = factory();
8 else if(typeof define === 'function' && define.amd)
9 define(factory);
10 else if(typeof exports === 'object')
11 exports["k2"] = factory();
12 else
13 root["k2"] = factory();
14})(this, function() {
15return /******/ (function(modules) { // webpackBootstrap
16/******/ // The module cache
17/******/ var installedModules = {};
18
19/******/ // The require function
20/******/ function __webpack_require__(moduleId) {
21
22/******/ // Check if module is in cache
23/******/ if(installedModules[moduleId])
24/******/ return installedModules[moduleId].exports;
25
26/******/ // Create a new module (and put it into the cache)
27/******/ var module = installedModules[moduleId] = {
28/******/ exports: {},
29/******/ id: moduleId,
30/******/ loaded: false
31/******/ };
32
33/******/ // Execute the module function
34/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
35
36/******/ // Flag the module as loaded
37/******/ module.loaded = true;
38
39/******/ // Return the exports of the module
40/******/ return module.exports;
41/******/ }
42
43
44/******/ // expose the modules object (__webpack_modules__)
45/******/ __webpack_require__.m = modules;
46
47/******/ // expose the module cache
48/******/ __webpack_require__.c = installedModules;
49
50/******/ // __webpack_public_path__
51/******/ __webpack_require__.p = "";
52
53/******/ // Load entry module and return exports
54/******/ return __webpack_require__(0);
55/******/ })
56/************************************************************************/
57/******/ ([
58/* 0 */
59/***/ function(module, exports, __webpack_require__) {
60
61 "use strict";
62
63 var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
64
65 var findPartialMatches = _interopRequire(__webpack_require__(1));
66
67 var rankPartialMatches = _interopRequire(__webpack_require__(2));
68
69 var cleanText = _interopRequire(__webpack_require__(3));
70
71 var objectLens = _interopRequire(__webpack_require__(4));
72
73 var guessDateFormat = _interopRequire(__webpack_require__(5));
74
75 var onlyTrue = _interopRequire(__webpack_require__(6));
76
77 var presentProperties = _interopRequire(__webpack_require__(7));
78
79 module.exports = {
80 findPartialMatches: findPartialMatches,
81 rankPartialMatches: rankPartialMatches,
82 cleanEnteredText: cleanText,
83 objectLens: objectLens,
84 guessDateFormat: guessDateFormat,
85 onlyTrue: onlyTrue,
86 presentProperties: presentProperties
87 };
88
89/***/ },
90/* 1 */
91/***/ function(module, exports, __webpack_require__) {
92
93 "use strict";
94
95 __webpack_require__(8);
96 var check = __webpack_require__(10);
97 var _ = __webpack_require__(9);
98
99 function findPartialMatchesSingleProperty(property, items, queryText) {
100 la(check.unemptyString(property), "need property name", property);
101 la(check.array(items), "expected list of items", items);
102 la(check.string(queryText), "expected query string", queryText);
103 if (!queryText) {
104 return [];
105 }
106
107 var text = queryText.toLowerCase();
108 function hasQueryText(item) {
109 return item[property].toLowerCase().indexOf(text) !== -1;
110 }
111
112 return items.filter(hasQueryText);
113 }
114
115 function findPartialMatchesMultipleProperties(properties, items, queryText) {
116 if (check.string(properties)) {
117 return findPartialMatchesSingleProperty(properties, items, queryText);
118 }
119 la(check.arrayOfStrings(properties), "need properties", properties);
120 la(check.array(items), "expected list of items", items);
121 la(check.string(queryText), "expected query string", queryText);
122 if (!queryText) {
123 return [];
124 }
125
126 var text = queryText.toLowerCase();
127 function hasQueryText(item) {
128 return properties.some(function (property) {
129 var value = item[property];
130 if (!value) {
131 return false;
132 }
133 return value.toLowerCase().indexOf(text) !== -1;
134 });
135 }
136
137 return items.filter(hasQueryText);
138 }
139
140 module.exports = findPartialMatchesMultipleProperties;
141
142/***/ },
143/* 2 */
144/***/ function(module, exports, __webpack_require__) {
145
146 "use strict";
147
148 __webpack_require__(8);
149 var check = __webpack_require__(10);
150 var _ = __webpack_require__(9);
151
152 // given objects that match query text, rank them, with better matches first
153 function rankPartialMatchesSingleProperty(property, matches, queryText) {
154 la(check.unemptyString(property), "need property name", property);
155 la(check.array(matches), "expected list of matches", matches);
156 la(check.string(queryText), "expected query string", queryText);
157 if (!matches.length || !queryText) {
158 return [];
159 }
160 var text = queryText.toLowerCase();
161
162 // ranks items, whereby a lower number is a better rank, assumes item
163 // matches the query string.
164 function rankMatch(item) {
165 var NOT_FOUND_RANK = 1000000;
166 var matchText = item[property].toLowerCase();
167 if (matchText === text) {
168 return -1;
169 }
170 var matchStartsAt = matchText.indexOf(text);
171 if (matchStartsAt === -1) {
172 return NOT_FOUND_RANK;
173 }
174 return matchStartsAt;
175 }
176
177 return _.sortBy(matches, rankMatch);
178 }
179
180 function rankPartialMatchesMultipleProperties(properties, matches, queryText) {
181 if (check.string(properties)) {
182 return rankPartialMatchesSingleProperty(properties, matches, queryText);
183 }
184 la(check.arrayOfStrings(properties), "need properties", properties);
185 la(check.array(matches), "expected list of matches", matches);
186 la(check.string(queryText), "expected query string", queryText);
187 if (!matches.length || !queryText) {
188 return [];
189 }
190 var text = queryText.toLowerCase();
191
192 // ranks items, whereby a lower number is a better rank, assumes item
193 // matches the query string.
194 function rankMatch(property, item) {
195 var NOT_FOUND_RANK = 1000000;
196 var matchText = item[property];
197 if (!matchText) {
198 return NOT_FOUND_RANK;
199 }
200 matchText = matchText.toLowerCase();
201 if (matchText === text) {
202 return -1;
203 }
204 var matchStartsAt = matchText.indexOf(text);
205 if (matchStartsAt === -1) {
206 return NOT_FOUND_RANK;
207 }
208 return matchStartsAt;
209 }
210
211 // best match over multiple properties is the smallest match
212 function rankMatches(item) {
213 var ranks = properties.map(function (property) {
214 return rankMatch(property, item);
215 });
216
217 return _.min(ranks);
218 }
219
220 return _.sortBy(matches, rankMatches);
221 }
222
223 module.exports = rankPartialMatchesMultipleProperties;
224
225/***/ },
226/* 3 */
227/***/ function(module, exports, __webpack_require__) {
228
229
230
231 /**
232 Removes HTML entities added by TextArea. Used in ticker search
233 @method cleanEnteredSearchText */
234 "use strict";
235
236 module.exports = cleanEnteredSearchText;
237 __webpack_require__(8);
238 var check = __webpack_require__(10);
239 var _ = __webpack_require__(9);
240 function cleanEnteredSearchText(str) {
241 la(check.string(str), "expected string to clean", str);
242 str = str.toLowerCase();
243 str = str.replace(" ", " ");
244 str = str.trim();
245 str = _.unescape(str);
246 return str;
247 }
248
249/***/ },
250/* 4 */
251/***/ function(module, exports, __webpack_require__) {
252
253 "use strict";
254
255 var R = __webpack_require__(11);
256
257 /**
258 Makes a lens for immutable object updates on the given key.
259 @method objectLens */
260 function objectLens(key) {
261 return R.lens(R.prop(key), function (val, obj) {
262 var child = Object.create(obj);
263 child.toJSON = function () {
264 var base;
265 if (obj.toJSON) {
266 base = obj.toJSON();
267 } else {
268 base = R.pick(Object.keys(obj), obj);
269 }
270 base[key] = val;
271 return base;
272 };
273 child[key] = val;
274 return child;
275 });
276 }
277
278 module.exports = objectLens;
279
280/***/ },
281/* 5 */
282/***/ function(module, exports, __webpack_require__) {
283
284 "use strict";
285
286 var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
287
288 __webpack_require__(8);
289 var check = __webpack_require__(10);
290
291 var xor = _interopRequire(__webpack_require__(6));
292
293 var isYear = function (x) {
294 return check.number(x) && x > 0;
295 };
296
297 var isMonth = function (x) {
298 return check.number(x) && x > 0 && x < 13;
299 };
300
301 var isDay = function (x) {
302 return check.number(x) && x > 0 && x < 32;
303 };
304
305 var validYearMonthDay = function (y, m, d) {
306 la(check.number(y) && check.number(m) && check.number(d), "invalid year or month or day", y, m, d);
307 return isYear(y) && isMonth(m) && isDay(d);
308 };
309
310 var isFormat = function (regex, str) {
311 la(check.instance(regex, RegExp), "expected regular expression", regex);
312 la(check.string(str), "expected string", str);
313 return regex.test(str);
314 };
315
316 var validIndices = check.schema.bind(null, {
317 year: check.number,
318 month: check.number,
319 day: check.number
320 });
321
322 var parseString = function (regex, indices, str) {
323 la(check.instance(regex, RegExp));
324 la(check.object(indices) && validIndices(indices), "missing indices", indices);
325 la(check.string(str), "missing date string", str);
326 var initial = check.unemptyString(str) && isFormat(regex, str);
327 if (!initial) {
328 return;
329 }
330 var matches = regex.exec(str);
331 return {
332 year: parseInt(matches[indices.year]),
333 month: parseInt(matches[indices.month]),
334 day: parseInt(matches[indices.day])
335 };
336 };
337
338 var parseIfPossible = function (regex, indices, str) {
339 var date = parseString(regex, indices, str);
340 if (date) {
341 la(validIndices(date), "missing date fields", date);
342 return validYearMonthDay(date.year, date.month, date.day);
343 }
344 };
345
346 var isYYYYMMDD = parseIfPossible.bind(null, /^(\d\d\d\d)[\-|\/](\d\d)\-(\d\d)$/, {
347 year: 1,
348 month: 2,
349 day: 3
350 });
351
352 var isYYYYDDMM = parseIfPossible.bind(null, /^(\d\d\d\d)\-(\d\d)\-(\d\d)$/, {
353 year: 1,
354 month: 3,
355 day: 2
356 });
357
358 var isDDMMYYYY = parseIfPossible.bind(null, /^(\d\d)[-|\/](\d\d?)[-|\/](\d\d\d\d)$/, {
359 year: 3,
360 month: 2,
361 day: 1
362 });
363
364 var isMMDDYYYY = parseIfPossible.bind(null, /^(\d\d)[-|\/](\d\d?)[-|\/](\d\d\d\d)$/, {
365 day: 2,
366 month: 1,
367 year: 3 });
368
369 function lift(fn) {
370 return function lifted(arr) {
371 return Array.isArray(arr) ? arr.every(fn) : fn(arr);
372 };
373 }
374
375 var formats = {
376 "YYYY-MM-DD": lift(isYYYYMMDD),
377 "YYYY-DD-MM": lift(isYYYYDDMM),
378 "DD-MM-YYYY": lift(isDDMMYYYY),
379 "MM-DD-YYYY": lift(isMMDDYYYY)
380 };
381
382 function findMatchedFormats(strings) {
383 var matchedFormats = [];
384 Object.keys(formats).forEach(function (format) {
385 var formatCheck = formats[format];
386 la(check.fn(formatCheck), "expected check function", format, formatCheck);
387 if (formatCheck(strings)) {
388 matchedFormats.push(format);
389 }
390 });
391 return matchedFormats;
392 }
393
394 function guessDateFormat(strings) {
395 if (!arguments.length) {
396 return;
397 }
398
399 var matchedFormats = findMatchedFormats(strings);
400 la(check.array(matchedFormats), "expected array result", matchedFormats, strings);
401
402 if (matchedFormats.length !== 1) {
403 // no matches or ambiguous dates
404 return;
405 }
406
407 return matchedFormats[0];
408 }
409
410 module.exports = guessDateFormat;
411
412/***/ },
413/* 6 */
414/***/ function(module, exports, __webpack_require__) {
415
416 /*
417 Returns true only if for the given list of predicates,
418 only single one is true, and the rest are false.
419
420 onlyTrue(true, false, false); // true
421 onlyTrue(false, false, false); // false
422 onlyTrue(false, true, true); // false
423 onlyTrue(false, false, true); // true
424 */
425 "use strict";
426
427 function onlyTrue() {
428 var predicates = Array.prototype.slice.call(arguments, 0);
429 if (!predicates.length) {
430 return false;
431 }
432 var count = 0,
433 k;
434 for (k = 0; k < predicates.length; k += 1) {
435 if (predicates[k]) {
436 count += 1;
437 if (count > 1) {
438 return false;
439 }
440 }
441 }
442
443 return count === 1;
444 }
445
446 module.exports = onlyTrue;
447
448/***/ },
449/* 7 */
450/***/ function(module, exports, __webpack_require__) {
451
452 "use strict";
453
454 __webpack_require__(8);
455 var check = __webpack_require__(10);
456 var _ = __webpack_require__(9);
457 la(check.fn(_.has), "missing lodash.has method, version upgrade?", _.VERSION);
458
459 function presentProperties(testProperties, list) {
460 la(check.arrayOf(check.unemptyString, testProperties), "missing test properties", testProperties);
461 la(check.array(list), "missing list of objects", list);
462
463 return testProperties.filter(function (key) {
464 return list.every(function (object) {
465 return _.has(object, key);
466 });
467 });
468 }
469
470 module.exports = _.curry(presentProperties);
471
472/***/ },
473/* 8 */
474/***/ function(module, exports, __webpack_require__) {
475
476 /* WEBPACK VAR INJECTION */(function(global) {(function initLazyAss() {
477
478 function isArrayLike(a) {
479 return a && typeof a.length === 'number';
480 }
481
482 function formMessage(args) {
483 var msg = args.reduce(function (total, arg, k) {
484 if (k) {
485 total += ' ';
486 }
487 if (typeof arg === 'string') {
488 return total + arg;
489 }
490 if (typeof arg === 'function') {
491 var fnResult;
492 try {
493 fnResult = arg();
494 } catch (err) {
495 // ignore the error
496 fnResult = '[function ' + arg.name + ' threw error!]';
497 }
498 return total + fnResult;
499 }
500 if (Array.isArray(arg)) {
501 return total + JSON.stringify(arg);
502 }
503 if (isArrayLike(arg)) {
504 return total + JSON.stringify(Array.prototype.slice.call(arg));
505 }
506 if (arg instanceof Error) {
507 return total + arg.name + ' ' + arg.message;
508 }
509 var argString;
510 try {
511 argString = JSON.stringify(arg, null, 2);
512 } catch (err) {
513 argString = '[cannot stringify arg ' + k + ']';
514 }
515 return total + argString;
516 }, '');
517 return msg;
518 }
519
520 function lazyAssLogic(condition) {
521 var fn = typeof condition === 'function' ? condition : null;
522
523 if (fn) {
524 condition = fn();
525 }
526 if (!condition) {
527 var args = [].slice.call(arguments, 1);
528 if (fn) {
529 args.unshift(fn.toString());
530 }
531 return new Error(formMessage(args));
532 }
533 }
534
535 var lazyAss = function lazyAss() {
536 var err = lazyAssLogic.apply(null, arguments);
537 if (err) {
538 throw err;
539 }
540 };
541
542 var lazyAssync = function lazyAssync() {
543 var err = lazyAssLogic.apply(null, arguments);
544 if (err) {
545 setTimeout(function () {
546 throw err;
547 }, 0);
548 }
549 };
550
551 function register(value, name) {
552 if (typeof window === 'object') {
553 /* global window */
554 window[name] = value;
555 } else if (typeof global === 'object') {
556 global[name] = value;
557 } else {
558 throw new Error('Do not know how to register ' + name);
559 }
560 }
561
562 register(lazyAss, 'lazyAss');
563 register(lazyAss, 'la');
564 register(lazyAssync, 'lazyAssync');
565 register(lazyAssync, 'lac');
566
567 }());
568
569 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
570
571/***/ },
572/* 9 */
573/***/ function(module, exports, __webpack_require__) {
574
575 var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/**
576 * @license
577 * lodash 3.10.0 (Custom Build) <https://lodash.com/>
578 * Build: `lodash modern -d -o ./index.js`
579 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
580 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
581 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
582 * Available under MIT license <https://lodash.com/license>
583 */
584 ;(function() {
585
586 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
587 var undefined;
588
589 /** Used as the semantic version number. */
590 var VERSION = '3.10.0';
591
592 /** Used to compose bitmasks for wrapper metadata. */
593 var BIND_FLAG = 1,
594 BIND_KEY_FLAG = 2,
595 CURRY_BOUND_FLAG = 4,
596 CURRY_FLAG = 8,
597 CURRY_RIGHT_FLAG = 16,
598 PARTIAL_FLAG = 32,
599 PARTIAL_RIGHT_FLAG = 64,
600 ARY_FLAG = 128,
601 REARG_FLAG = 256;
602
603 /** Used as default options for `_.trunc`. */
604 var DEFAULT_TRUNC_LENGTH = 30,
605 DEFAULT_TRUNC_OMISSION = '...';
606
607 /** Used to detect when a function becomes hot. */
608 var HOT_COUNT = 150,
609 HOT_SPAN = 16;
610
611 /** Used as the size to enable large array optimizations. */
612 var LARGE_ARRAY_SIZE = 200;
613
614 /** Used to indicate the type of lazy iteratees. */
615 var LAZY_FILTER_FLAG = 1,
616 LAZY_MAP_FLAG = 2;
617
618 /** Used as the `TypeError` message for "Functions" methods. */
619 var FUNC_ERROR_TEXT = 'Expected a function';
620
621 /** Used as the internal argument placeholder. */
622 var PLACEHOLDER = '__lodash_placeholder__';
623
624 /** `Object#toString` result references. */
625 var argsTag = '[object Arguments]',
626 arrayTag = '[object Array]',
627 boolTag = '[object Boolean]',
628 dateTag = '[object Date]',
629 errorTag = '[object Error]',
630 funcTag = '[object Function]',
631 mapTag = '[object Map]',
632 numberTag = '[object Number]',
633 objectTag = '[object Object]',
634 regexpTag = '[object RegExp]',
635 setTag = '[object Set]',
636 stringTag = '[object String]',
637 weakMapTag = '[object WeakMap]';
638
639 var arrayBufferTag = '[object ArrayBuffer]',
640 float32Tag = '[object Float32Array]',
641 float64Tag = '[object Float64Array]',
642 int8Tag = '[object Int8Array]',
643 int16Tag = '[object Int16Array]',
644 int32Tag = '[object Int32Array]',
645 uint8Tag = '[object Uint8Array]',
646 uint8ClampedTag = '[object Uint8ClampedArray]',
647 uint16Tag = '[object Uint16Array]',
648 uint32Tag = '[object Uint32Array]';
649
650 /** Used to match empty string literals in compiled template source. */
651 var reEmptyStringLeading = /\b__p \+= '';/g,
652 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
653 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
654
655 /** Used to match HTML entities and HTML characters. */
656 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
657 reUnescapedHtml = /[&<>"'`]/g,
658 reHasEscapedHtml = RegExp(reEscapedHtml.source),
659 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
660
661 /** Used to match template delimiters. */
662 var reEscape = /<%-([\s\S]+?)%>/g,
663 reEvaluate = /<%([\s\S]+?)%>/g,
664 reInterpolate = /<%=([\s\S]+?)%>/g;
665
666 /** Used to match property names within property paths. */
667 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
668 reIsPlainProp = /^\w*$/,
669 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
670
671 /**
672 * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
673 * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
674 */
675 var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
676 reHasRegExpChars = RegExp(reRegExpChars.source);
677
678 /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
679 var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
680
681 /** Used to match backslashes in property paths. */
682 var reEscapeChar = /\\(\\)?/g;
683
684 /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
685 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
686
687 /** Used to match `RegExp` flags from their coerced string values. */
688 var reFlags = /\w*$/;
689
690 /** Used to detect hexadecimal string values. */
691 var reHasHexPrefix = /^0[xX]/;
692
693 /** Used to detect host constructors (Safari > 5). */
694 var reIsHostCtor = /^\[object .+?Constructor\]$/;
695
696 /** Used to detect unsigned integer values. */
697 var reIsUint = /^\d+$/;
698
699 /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
700 var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
701
702 /** Used to ensure capturing order of template delimiters. */
703 var reNoMatch = /($^)/;
704
705 /** Used to match unescaped characters in compiled string literals. */
706 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
707
708 /** Used to match words to create compound words. */
709 var reWords = (function() {
710 var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
711 lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
712
713 return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
714 }());
715
716 /** Used to assign default `context` object properties. */
717 var contextProps = [
718 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
719 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
720 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite',
721 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
722 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap'
723 ];
724
725 /** Used to make template sourceURLs easier to identify. */
726 var templateCounter = -1;
727
728 /** Used to identify `toStringTag` values of typed arrays. */
729 var typedArrayTags = {};
730 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
731 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
732 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
733 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
734 typedArrayTags[uint32Tag] = true;
735 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
736 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
737 typedArrayTags[dateTag] = typedArrayTags[errorTag] =
738 typedArrayTags[funcTag] = typedArrayTags[mapTag] =
739 typedArrayTags[numberTag] = typedArrayTags[objectTag] =
740 typedArrayTags[regexpTag] = typedArrayTags[setTag] =
741 typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
742
743 /** Used to identify `toStringTag` values supported by `_.clone`. */
744 var cloneableTags = {};
745 cloneableTags[argsTag] = cloneableTags[arrayTag] =
746 cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
747 cloneableTags[dateTag] = cloneableTags[float32Tag] =
748 cloneableTags[float64Tag] = cloneableTags[int8Tag] =
749 cloneableTags[int16Tag] = cloneableTags[int32Tag] =
750 cloneableTags[numberTag] = cloneableTags[objectTag] =
751 cloneableTags[regexpTag] = cloneableTags[stringTag] =
752 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
753 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
754 cloneableTags[errorTag] = cloneableTags[funcTag] =
755 cloneableTags[mapTag] = cloneableTags[setTag] =
756 cloneableTags[weakMapTag] = false;
757
758 /** Used to map latin-1 supplementary letters to basic latin letters. */
759 var deburredLetters = {
760 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
761 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
762 '\xc7': 'C', '\xe7': 'c',
763 '\xd0': 'D', '\xf0': 'd',
764 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
765 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
766 '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
767 '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
768 '\xd1': 'N', '\xf1': 'n',
769 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
770 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
771 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
772 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
773 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
774 '\xc6': 'Ae', '\xe6': 'ae',
775 '\xde': 'Th', '\xfe': 'th',
776 '\xdf': 'ss'
777 };
778
779 /** Used to map characters to HTML entities. */
780 var htmlEscapes = {
781 '&': '&amp;',
782 '<': '&lt;',
783 '>': '&gt;',
784 '"': '&quot;',
785 "'": '&#39;',
786 '`': '&#96;'
787 };
788
789 /** Used to map HTML entities to characters. */
790 var htmlUnescapes = {
791 '&amp;': '&',
792 '&lt;': '<',
793 '&gt;': '>',
794 '&quot;': '"',
795 '&#39;': "'",
796 '&#96;': '`'
797 };
798
799 /** Used to determine if values are of the language type `Object`. */
800 var objectTypes = {
801 'function': true,
802 'object': true
803 };
804
805 /** Used to escape characters for inclusion in compiled regexes. */
806 var regexpEscapes = {
807 '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34',
808 '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39',
809 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46',
810 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66',
811 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78'
812 };
813
814 /** Used to escape characters for inclusion in compiled string literals. */
815 var stringEscapes = {
816 '\\': '\\',
817 "'": "'",
818 '\n': 'n',
819 '\r': 'r',
820 '\u2028': 'u2028',
821 '\u2029': 'u2029'
822 };
823
824 /** Detect free variable `exports`. */
825 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
826
827 /** Detect free variable `module`. */
828 var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
829
830 /** Detect free variable `global` from Node.js. */
831 var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
832
833 /** Detect free variable `self`. */
834 var freeSelf = objectTypes[typeof self] && self && self.Object && self;
835
836 /** Detect free variable `window`. */
837 var freeWindow = objectTypes[typeof window] && window && window.Object && window;
838
839 /** Detect the popular CommonJS extension `module.exports`. */
840 var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
841
842 /**
843 * Used as a reference to the global object.
844 *
845 * The `this` value is used if it's the global object to avoid Greasemonkey's
846 * restricted `window` object, otherwise the `window` object is used.
847 */
848 var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
849
850 /*--------------------------------------------------------------------------*/
851
852 /**
853 * The base implementation of `compareAscending` which compares values and
854 * sorts them in ascending order without guaranteeing a stable sort.
855 *
856 * @private
857 * @param {*} value The value to compare.
858 * @param {*} other The other value to compare.
859 * @returns {number} Returns the sort order indicator for `value`.
860 */
861 function baseCompareAscending(value, other) {
862 if (value !== other) {
863 var valIsNull = value === null,
864 valIsUndef = value === undefined,
865 valIsReflexive = value === value;
866
867 var othIsNull = other === null,
868 othIsUndef = other === undefined,
869 othIsReflexive = other === other;
870
871 if ((value > other && !othIsNull) || !valIsReflexive ||
872 (valIsNull && !othIsUndef && othIsReflexive) ||
873 (valIsUndef && othIsReflexive)) {
874 return 1;
875 }
876 if ((value < other && !valIsNull) || !othIsReflexive ||
877 (othIsNull && !valIsUndef && valIsReflexive) ||
878 (othIsUndef && valIsReflexive)) {
879 return -1;
880 }
881 }
882 return 0;
883 }
884
885 /**
886 * The base implementation of `_.findIndex` and `_.findLastIndex` without
887 * support for callback shorthands and `this` binding.
888 *
889 * @private
890 * @param {Array} array The array to search.
891 * @param {Function} predicate The function invoked per iteration.
892 * @param {boolean} [fromRight] Specify iterating from right to left.
893 * @returns {number} Returns the index of the matched value, else `-1`.
894 */
895 function baseFindIndex(array, predicate, fromRight) {
896 var length = array.length,
897 index = fromRight ? length : -1;
898
899 while ((fromRight ? index-- : ++index < length)) {
900 if (predicate(array[index], index, array)) {
901 return index;
902 }
903 }
904 return -1;
905 }
906
907 /**
908 * The base implementation of `_.indexOf` without support for binary searches.
909 *
910 * @private
911 * @param {Array} array The array to search.
912 * @param {*} value The value to search for.
913 * @param {number} fromIndex The index to search from.
914 * @returns {number} Returns the index of the matched value, else `-1`.
915 */
916 function baseIndexOf(array, value, fromIndex) {
917 if (value !== value) {
918 return indexOfNaN(array, fromIndex);
919 }
920 var index = fromIndex - 1,
921 length = array.length;
922
923 while (++index < length) {
924 if (array[index] === value) {
925 return index;
926 }
927 }
928 return -1;
929 }
930
931 /**
932 * The base implementation of `_.isFunction` without support for environments
933 * with incorrect `typeof` results.
934 *
935 * @private
936 * @param {*} value The value to check.
937 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
938 */
939 function baseIsFunction(value) {
940 // Avoid a Chakra JIT bug in compatibility modes of IE 11.
941 // See https://github.com/jashkenas/underscore/issues/1621 for more details.
942 return typeof value == 'function' || false;
943 }
944
945 /**
946 * Converts `value` to a string if it's not one. An empty string is returned
947 * for `null` or `undefined` values.
948 *
949 * @private
950 * @param {*} value The value to process.
951 * @returns {string} Returns the string.
952 */
953 function baseToString(value) {
954 return value == null ? '' : (value + '');
955 }
956
957 /**
958 * Used by `_.trim` and `_.trimLeft` to get the index of the first character
959 * of `string` that is not found in `chars`.
960 *
961 * @private
962 * @param {string} string The string to inspect.
963 * @param {string} chars The characters to find.
964 * @returns {number} Returns the index of the first character not found in `chars`.
965 */
966 function charsLeftIndex(string, chars) {
967 var index = -1,
968 length = string.length;
969
970 while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
971 return index;
972 }
973
974 /**
975 * Used by `_.trim` and `_.trimRight` to get the index of the last character
976 * of `string` that is not found in `chars`.
977 *
978 * @private
979 * @param {string} string The string to inspect.
980 * @param {string} chars The characters to find.
981 * @returns {number} Returns the index of the last character not found in `chars`.
982 */
983 function charsRightIndex(string, chars) {
984 var index = string.length;
985
986 while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
987 return index;
988 }
989
990 /**
991 * Used by `_.sortBy` to compare transformed elements of a collection and stable
992 * sort them in ascending order.
993 *
994 * @private
995 * @param {Object} object The object to compare.
996 * @param {Object} other The other object to compare.
997 * @returns {number} Returns the sort order indicator for `object`.
998 */
999 function compareAscending(object, other) {
1000 return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
1001 }
1002
1003 /**
1004 * Used by `_.sortByOrder` to compare multiple properties of a value to another
1005 * and stable sort them.
1006 *
1007 * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
1008 * a value is sorted in ascending order if its corresponding order is "asc", and
1009 * descending if "desc".
1010 *
1011 * @private
1012 * @param {Object} object The object to compare.
1013 * @param {Object} other The other object to compare.
1014 * @param {boolean[]} orders The order to sort by for each property.
1015 * @returns {number} Returns the sort order indicator for `object`.
1016 */
1017 function compareMultiple(object, other, orders) {
1018 var index = -1,
1019 objCriteria = object.criteria,
1020 othCriteria = other.criteria,
1021 length = objCriteria.length,
1022 ordersLength = orders.length;
1023
1024 while (++index < length) {
1025 var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
1026 if (result) {
1027 if (index >= ordersLength) {
1028 return result;
1029 }
1030 var order = orders[index];
1031 return result * ((order === 'asc' || order === true) ? 1 : -1);
1032 }
1033 }
1034 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
1035 // that causes it, under certain circumstances, to provide the same value for
1036 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
1037 // for more details.
1038 //
1039 // This also ensures a stable sort in V8 and other engines.
1040 // See https://code.google.com/p/v8/issues/detail?id=90 for more details.
1041 return object.index - other.index;
1042 }
1043
1044 /**
1045 * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
1046 *
1047 * @private
1048 * @param {string} letter The matched letter to deburr.
1049 * @returns {string} Returns the deburred letter.
1050 */
1051 function deburrLetter(letter) {
1052 return deburredLetters[letter];
1053 }
1054
1055 /**
1056 * Used by `_.escape` to convert characters to HTML entities.
1057 *
1058 * @private
1059 * @param {string} chr The matched character to escape.
1060 * @returns {string} Returns the escaped character.
1061 */
1062 function escapeHtmlChar(chr) {
1063 return htmlEscapes[chr];
1064 }
1065
1066 /**
1067 * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
1068 *
1069 * @private
1070 * @param {string} chr The matched character to escape.
1071 * @param {string} leadingChar The capture group for a leading character.
1072 * @param {string} whitespaceChar The capture group for a whitespace character.
1073 * @returns {string} Returns the escaped character.
1074 */
1075 function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
1076 if (leadingChar) {
1077 chr = regexpEscapes[chr];
1078 } else if (whitespaceChar) {
1079 chr = stringEscapes[chr];
1080 }
1081 return '\\' + chr;
1082 }
1083
1084 /**
1085 * Used by `_.template` to escape characters for inclusion in compiled string literals.
1086 *
1087 * @private
1088 * @param {string} chr The matched character to escape.
1089 * @returns {string} Returns the escaped character.
1090 */
1091 function escapeStringChar(chr) {
1092 return '\\' + stringEscapes[chr];
1093 }
1094
1095 /**
1096 * Gets the index at which the first occurrence of `NaN` is found in `array`.
1097 *
1098 * @private
1099 * @param {Array} array The array to search.
1100 * @param {number} fromIndex The index to search from.
1101 * @param {boolean} [fromRight] Specify iterating from right to left.
1102 * @returns {number} Returns the index of the matched `NaN`, else `-1`.
1103 */
1104 function indexOfNaN(array, fromIndex, fromRight) {
1105 var length = array.length,
1106 index = fromIndex + (fromRight ? 0 : -1);
1107
1108 while ((fromRight ? index-- : ++index < length)) {
1109 var other = array[index];
1110 if (other !== other) {
1111 return index;
1112 }
1113 }
1114 return -1;
1115 }
1116
1117 /**
1118 * Checks if `value` is object-like.
1119 *
1120 * @private
1121 * @param {*} value The value to check.
1122 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
1123 */
1124 function isObjectLike(value) {
1125 return !!value && typeof value == 'object';
1126 }
1127
1128 /**
1129 * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
1130 * character code is whitespace.
1131 *
1132 * @private
1133 * @param {number} charCode The character code to inspect.
1134 * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
1135 */
1136 function isSpace(charCode) {
1137 return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
1138 (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
1139 }
1140
1141 /**
1142 * Replaces all `placeholder` elements in `array` with an internal placeholder
1143 * and returns an array of their indexes.
1144 *
1145 * @private
1146 * @param {Array} array The array to modify.
1147 * @param {*} placeholder The placeholder to replace.
1148 * @returns {Array} Returns the new array of placeholder indexes.
1149 */
1150 function replaceHolders(array, placeholder) {
1151 var index = -1,
1152 length = array.length,
1153 resIndex = -1,
1154 result = [];
1155
1156 while (++index < length) {
1157 if (array[index] === placeholder) {
1158 array[index] = PLACEHOLDER;
1159 result[++resIndex] = index;
1160 }
1161 }
1162 return result;
1163 }
1164
1165 /**
1166 * An implementation of `_.uniq` optimized for sorted arrays without support
1167 * for callback shorthands and `this` binding.
1168 *
1169 * @private
1170 * @param {Array} array The array to inspect.
1171 * @param {Function} [iteratee] The function invoked per iteration.
1172 * @returns {Array} Returns the new duplicate-value-free array.
1173 */
1174 function sortedUniq(array, iteratee) {
1175 var seen,
1176 index = -1,
1177 length = array.length,
1178 resIndex = -1,
1179 result = [];
1180
1181 while (++index < length) {
1182 var value = array[index],
1183 computed = iteratee ? iteratee(value, index, array) : value;
1184
1185 if (!index || seen !== computed) {
1186 seen = computed;
1187 result[++resIndex] = value;
1188 }
1189 }
1190 return result;
1191 }
1192
1193 /**
1194 * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
1195 * character of `string`.
1196 *
1197 * @private
1198 * @param {string} string The string to inspect.
1199 * @returns {number} Returns the index of the first non-whitespace character.
1200 */
1201 function trimmedLeftIndex(string) {
1202 var index = -1,
1203 length = string.length;
1204
1205 while (++index < length && isSpace(string.charCodeAt(index))) {}
1206 return index;
1207 }
1208
1209 /**
1210 * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
1211 * character of `string`.
1212 *
1213 * @private
1214 * @param {string} string The string to inspect.
1215 * @returns {number} Returns the index of the last non-whitespace character.
1216 */
1217 function trimmedRightIndex(string) {
1218 var index = string.length;
1219
1220 while (index-- && isSpace(string.charCodeAt(index))) {}
1221 return index;
1222 }
1223
1224 /**
1225 * Used by `_.unescape` to convert HTML entities to characters.
1226 *
1227 * @private
1228 * @param {string} chr The matched character to unescape.
1229 * @returns {string} Returns the unescaped character.
1230 */
1231 function unescapeHtmlChar(chr) {
1232 return htmlUnescapes[chr];
1233 }
1234
1235 /*--------------------------------------------------------------------------*/
1236
1237 /**
1238 * Create a new pristine `lodash` function using the given `context` object.
1239 *
1240 * @static
1241 * @memberOf _
1242 * @category Utility
1243 * @param {Object} [context=root] The context object.
1244 * @returns {Function} Returns a new `lodash` function.
1245 * @example
1246 *
1247 * _.mixin({ 'foo': _.constant('foo') });
1248 *
1249 * var lodash = _.runInContext();
1250 * lodash.mixin({ 'bar': lodash.constant('bar') });
1251 *
1252 * _.isFunction(_.foo);
1253 * // => true
1254 * _.isFunction(_.bar);
1255 * // => false
1256 *
1257 * lodash.isFunction(lodash.foo);
1258 * // => false
1259 * lodash.isFunction(lodash.bar);
1260 * // => true
1261 *
1262 * // using `context` to mock `Date#getTime` use in `_.now`
1263 * var mock = _.runInContext({
1264 * 'Date': function() {
1265 * return { 'getTime': getTimeMock };
1266 * }
1267 * });
1268 *
1269 * // or creating a suped-up `defer` in Node.js
1270 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
1271 */
1272 function runInContext(context) {
1273 // Avoid issues with some ES3 environments that attempt to use values, named
1274 // after built-in constructors like `Object`, for the creation of literals.
1275 // ES5 clears this up by stating that literals must use built-in constructors.
1276 // See https://es5.github.io/#x11.1.5 for more details.
1277 context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
1278
1279 /** Native constructor references. */
1280 var Array = context.Array,
1281 Date = context.Date,
1282 Error = context.Error,
1283 Function = context.Function,
1284 Math = context.Math,
1285 Number = context.Number,
1286 Object = context.Object,
1287 RegExp = context.RegExp,
1288 String = context.String,
1289 TypeError = context.TypeError;
1290
1291 /** Used for native method references. */
1292 var arrayProto = Array.prototype,
1293 objectProto = Object.prototype,
1294 stringProto = String.prototype;
1295
1296 /** Used to resolve the decompiled source of functions. */
1297 var fnToString = Function.prototype.toString;
1298
1299 /** Used to check objects for own properties. */
1300 var hasOwnProperty = objectProto.hasOwnProperty;
1301
1302 /** Used to generate unique IDs. */
1303 var idCounter = 0;
1304
1305 /**
1306 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
1307 * of values.
1308 */
1309 var objToString = objectProto.toString;
1310
1311 /** Used to restore the original `_` reference in `_.noConflict`. */
1312 var oldDash = root._;
1313
1314 /** Used to detect if a method is native. */
1315 var reIsNative = RegExp('^' +
1316 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
1317 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
1318 );
1319
1320 /** Native method references. */
1321 var ArrayBuffer = context.ArrayBuffer,
1322 clearTimeout = context.clearTimeout,
1323 parseFloat = context.parseFloat,
1324 pow = Math.pow,
1325 propertyIsEnumerable = objectProto.propertyIsEnumerable,
1326 Set = getNative(context, 'Set'),
1327 setTimeout = context.setTimeout,
1328 splice = arrayProto.splice,
1329 Uint8Array = context.Uint8Array,
1330 WeakMap = getNative(context, 'WeakMap');
1331
1332 /* Native method references for those with the same name as other `lodash` methods. */
1333 var nativeCeil = Math.ceil,
1334 nativeCreate = getNative(Object, 'create'),
1335 nativeFloor = Math.floor,
1336 nativeIsArray = getNative(Array, 'isArray'),
1337 nativeIsFinite = context.isFinite,
1338 nativeKeys = getNative(Object, 'keys'),
1339 nativeMax = Math.max,
1340 nativeMin = Math.min,
1341 nativeNow = getNative(Date, 'now'),
1342 nativeParseInt = context.parseInt,
1343 nativeRandom = Math.random;
1344
1345 /** Used as references for `-Infinity` and `Infinity`. */
1346 var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
1347 POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
1348
1349 /** Used as references for the maximum length and index of an array. */
1350 var MAX_ARRAY_LENGTH = 4294967295,
1351 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
1352 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
1353
1354 /**
1355 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
1356 * of an array-like value.
1357 */
1358 var MAX_SAFE_INTEGER = 9007199254740991;
1359
1360 /** Used to store function metadata. */
1361 var metaMap = WeakMap && new WeakMap;
1362
1363 /** Used to lookup unminified function names. */
1364 var realNames = {};
1365
1366 /*------------------------------------------------------------------------*/
1367
1368 /**
1369 * Creates a `lodash` object which wraps `value` to enable implicit chaining.
1370 * Methods that operate on and return arrays, collections, and functions can
1371 * be chained together. Methods that retrieve a single value or may return a
1372 * primitive value will automatically end the chain returning the unwrapped
1373 * value. Explicit chaining may be enabled using `_.chain`. The execution of
1374 * chained methods is lazy, that is, execution is deferred until `_#value`
1375 * is implicitly or explicitly called.
1376 *
1377 * Lazy evaluation allows several methods to support shortcut fusion. Shortcut
1378 * fusion is an optimization strategy which merge iteratee calls; this can help
1379 * to avoid the creation of intermediate data structures and greatly reduce the
1380 * number of iteratee executions.
1381 *
1382 * Chaining is supported in custom builds as long as the `_#value` method is
1383 * directly or indirectly included in the build.
1384 *
1385 * In addition to lodash methods, wrappers have `Array` and `String` methods.
1386 *
1387 * The wrapper `Array` methods are:
1388 * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
1389 * `splice`, and `unshift`
1390 *
1391 * The wrapper `String` methods are:
1392 * `replace` and `split`
1393 *
1394 * The wrapper methods that support shortcut fusion are:
1395 * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
1396 * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
1397 * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
1398 * and `where`
1399 *
1400 * The chainable wrapper methods are:
1401 * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
1402 * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
1403 * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
1404 * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
1405 * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
1406 * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
1407 * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
1408 * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
1409 * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
1410 * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
1411 * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
1412 * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
1413 * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
1414 * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
1415 * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
1416 * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
1417 * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
1418 *
1419 * The wrapper methods that are **not** chainable by default are:
1420 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
1421 * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
1422 * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
1423 * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
1424 * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
1425 * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
1426 * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
1427 * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
1428 * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
1429 * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
1430 * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
1431 * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
1432 * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
1433 * `unescape`, `uniqueId`, `value`, and `words`
1434 *
1435 * The wrapper method `sample` will return a wrapped value when `n` is provided,
1436 * otherwise an unwrapped value is returned.
1437 *
1438 * @name _
1439 * @constructor
1440 * @category Chain
1441 * @param {*} value The value to wrap in a `lodash` instance.
1442 * @returns {Object} Returns the new `lodash` wrapper instance.
1443 * @example
1444 *
1445 * var wrapped = _([1, 2, 3]);
1446 *
1447 * // returns an unwrapped value
1448 * wrapped.reduce(function(total, n) {
1449 * return total + n;
1450 * });
1451 * // => 6
1452 *
1453 * // returns a wrapped value
1454 * var squares = wrapped.map(function(n) {
1455 * return n * n;
1456 * });
1457 *
1458 * _.isArray(squares);
1459 * // => false
1460 *
1461 * _.isArray(squares.value());
1462 * // => true
1463 */
1464 function lodash(value) {
1465 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
1466 if (value instanceof LodashWrapper) {
1467 return value;
1468 }
1469 if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
1470 return wrapperClone(value);
1471 }
1472 }
1473 return new LodashWrapper(value);
1474 }
1475
1476 /**
1477 * The function whose prototype all chaining wrappers inherit from.
1478 *
1479 * @private
1480 */
1481 function baseLodash() {
1482 // No operation performed.
1483 }
1484
1485 /**
1486 * The base constructor for creating `lodash` wrapper objects.
1487 *
1488 * @private
1489 * @param {*} value The value to wrap.
1490 * @param {boolean} [chainAll] Enable chaining for all wrapper methods.
1491 * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
1492 */
1493 function LodashWrapper(value, chainAll, actions) {
1494 this.__wrapped__ = value;
1495 this.__actions__ = actions || [];
1496 this.__chain__ = !!chainAll;
1497 }
1498
1499 /**
1500 * An object environment feature flags.
1501 *
1502 * @static
1503 * @memberOf _
1504 * @type Object
1505 */
1506 var support = lodash.support = {};
1507
1508 /**
1509 * By default, the template delimiters used by lodash are like those in
1510 * embedded Ruby (ERB). Change the following template settings to use
1511 * alternative delimiters.
1512 *
1513 * @static
1514 * @memberOf _
1515 * @type Object
1516 */
1517 lodash.templateSettings = {
1518
1519 /**
1520 * Used to detect `data` property values to be HTML-escaped.
1521 *
1522 * @memberOf _.templateSettings
1523 * @type RegExp
1524 */
1525 'escape': reEscape,
1526
1527 /**
1528 * Used to detect code to be evaluated.
1529 *
1530 * @memberOf _.templateSettings
1531 * @type RegExp
1532 */
1533 'evaluate': reEvaluate,
1534
1535 /**
1536 * Used to detect `data` property values to inject.
1537 *
1538 * @memberOf _.templateSettings
1539 * @type RegExp
1540 */
1541 'interpolate': reInterpolate,
1542
1543 /**
1544 * Used to reference the data object in the template text.
1545 *
1546 * @memberOf _.templateSettings
1547 * @type string
1548 */
1549 'variable': '',
1550
1551 /**
1552 * Used to import variables into the compiled template.
1553 *
1554 * @memberOf _.templateSettings
1555 * @type Object
1556 */
1557 'imports': {
1558
1559 /**
1560 * A reference to the `lodash` function.
1561 *
1562 * @memberOf _.templateSettings.imports
1563 * @type Function
1564 */
1565 '_': lodash
1566 }
1567 };
1568
1569 /*------------------------------------------------------------------------*/
1570
1571 /**
1572 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
1573 *
1574 * @private
1575 * @param {*} value The value to wrap.
1576 */
1577 function LazyWrapper(value) {
1578 this.__wrapped__ = value;
1579 this.__actions__ = [];
1580 this.__dir__ = 1;
1581 this.__filtered__ = false;
1582 this.__iteratees__ = [];
1583 this.__takeCount__ = POSITIVE_INFINITY;
1584 this.__views__ = [];
1585 }
1586
1587 /**
1588 * Creates a clone of the lazy wrapper object.
1589 *
1590 * @private
1591 * @name clone
1592 * @memberOf LazyWrapper
1593 * @returns {Object} Returns the cloned `LazyWrapper` object.
1594 */
1595 function lazyClone() {
1596 var result = new LazyWrapper(this.__wrapped__);
1597 result.__actions__ = arrayCopy(this.__actions__);
1598 result.__dir__ = this.__dir__;
1599 result.__filtered__ = this.__filtered__;
1600 result.__iteratees__ = arrayCopy(this.__iteratees__);
1601 result.__takeCount__ = this.__takeCount__;
1602 result.__views__ = arrayCopy(this.__views__);
1603 return result;
1604 }
1605
1606 /**
1607 * Reverses the direction of lazy iteration.
1608 *
1609 * @private
1610 * @name reverse
1611 * @memberOf LazyWrapper
1612 * @returns {Object} Returns the new reversed `LazyWrapper` object.
1613 */
1614 function lazyReverse() {
1615 if (this.__filtered__) {
1616 var result = new LazyWrapper(this);
1617 result.__dir__ = -1;
1618 result.__filtered__ = true;
1619 } else {
1620 result = this.clone();
1621 result.__dir__ *= -1;
1622 }
1623 return result;
1624 }
1625
1626 /**
1627 * Extracts the unwrapped value from its lazy wrapper.
1628 *
1629 * @private
1630 * @name value
1631 * @memberOf LazyWrapper
1632 * @returns {*} Returns the unwrapped value.
1633 */
1634 function lazyValue() {
1635 var array = this.__wrapped__.value(),
1636 dir = this.__dir__,
1637 isArr = isArray(array),
1638 isRight = dir < 0,
1639 arrLength = isArr ? array.length : 0,
1640 view = getView(0, arrLength, this.__views__),
1641 start = view.start,
1642 end = view.end,
1643 length = end - start,
1644 index = isRight ? end : (start - 1),
1645 iteratees = this.__iteratees__,
1646 iterLength = iteratees.length,
1647 resIndex = 0,
1648 takeCount = nativeMin(length, this.__takeCount__);
1649
1650 if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) {
1651 return baseWrapperValue((isRight && isArr) ? array.reverse() : array, this.__actions__);
1652 }
1653 var result = [];
1654
1655 outer:
1656 while (length-- && resIndex < takeCount) {
1657 index += dir;
1658
1659 var iterIndex = -1,
1660 value = array[index];
1661
1662 while (++iterIndex < iterLength) {
1663 var data = iteratees[iterIndex],
1664 iteratee = data.iteratee,
1665 type = data.type,
1666 computed = iteratee(value);
1667
1668 if (type == LAZY_MAP_FLAG) {
1669 value = computed;
1670 } else if (!computed) {
1671 if (type == LAZY_FILTER_FLAG) {
1672 continue outer;
1673 } else {
1674 break outer;
1675 }
1676 }
1677 }
1678 result[resIndex++] = value;
1679 }
1680 return result;
1681 }
1682
1683 /*------------------------------------------------------------------------*/
1684
1685 /**
1686 * Creates a cache object to store key/value pairs.
1687 *
1688 * @private
1689 * @static
1690 * @name Cache
1691 * @memberOf _.memoize
1692 */
1693 function MapCache() {
1694 this.__data__ = {};
1695 }
1696
1697 /**
1698 * Removes `key` and its value from the cache.
1699 *
1700 * @private
1701 * @name delete
1702 * @memberOf _.memoize.Cache
1703 * @param {string} key The key of the value to remove.
1704 * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
1705 */
1706 function mapDelete(key) {
1707 return this.has(key) && delete this.__data__[key];
1708 }
1709
1710 /**
1711 * Gets the cached value for `key`.
1712 *
1713 * @private
1714 * @name get
1715 * @memberOf _.memoize.Cache
1716 * @param {string} key The key of the value to get.
1717 * @returns {*} Returns the cached value.
1718 */
1719 function mapGet(key) {
1720 return key == '__proto__' ? undefined : this.__data__[key];
1721 }
1722
1723 /**
1724 * Checks if a cached value for `key` exists.
1725 *
1726 * @private
1727 * @name has
1728 * @memberOf _.memoize.Cache
1729 * @param {string} key The key of the entry to check.
1730 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1731 */
1732 function mapHas(key) {
1733 return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
1734 }
1735
1736 /**
1737 * Sets `value` to `key` of the cache.
1738 *
1739 * @private
1740 * @name set
1741 * @memberOf _.memoize.Cache
1742 * @param {string} key The key of the value to cache.
1743 * @param {*} value The value to cache.
1744 * @returns {Object} Returns the cache object.
1745 */
1746 function mapSet(key, value) {
1747 if (key != '__proto__') {
1748 this.__data__[key] = value;
1749 }
1750 return this;
1751 }
1752
1753 /*------------------------------------------------------------------------*/
1754
1755 /**
1756 *
1757 * Creates a cache object to store unique values.
1758 *
1759 * @private
1760 * @param {Array} [values] The values to cache.
1761 */
1762 function SetCache(values) {
1763 var length = values ? values.length : 0;
1764
1765 this.data = { 'hash': nativeCreate(null), 'set': new Set };
1766 while (length--) {
1767 this.push(values[length]);
1768 }
1769 }
1770
1771 /**
1772 * Checks if `value` is in `cache` mimicking the return signature of
1773 * `_.indexOf` by returning `0` if the value is found, else `-1`.
1774 *
1775 * @private
1776 * @param {Object} cache The cache to search.
1777 * @param {*} value The value to search for.
1778 * @returns {number} Returns `0` if `value` is found, else `-1`.
1779 */
1780 function cacheIndexOf(cache, value) {
1781 var data = cache.data,
1782 result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
1783
1784 return result ? 0 : -1;
1785 }
1786
1787 /**
1788 * Adds `value` to the cache.
1789 *
1790 * @private
1791 * @name push
1792 * @memberOf SetCache
1793 * @param {*} value The value to cache.
1794 */
1795 function cachePush(value) {
1796 var data = this.data;
1797 if (typeof value == 'string' || isObject(value)) {
1798 data.set.add(value);
1799 } else {
1800 data.hash[value] = true;
1801 }
1802 }
1803
1804 /*------------------------------------------------------------------------*/
1805
1806 /**
1807 * Creates a new array joining `array` with `other`.
1808 *
1809 * @private
1810 * @param {Array} array The array to join.
1811 * @param {Array} other The other array to join.
1812 * @returns {Array} Returns the new concatenated array.
1813 */
1814 function arrayConcat(array, other) {
1815 var index = -1,
1816 length = array.length,
1817 othIndex = -1,
1818 othLength = other.length,
1819 result = Array(length + othLength);
1820
1821 while (++index < length) {
1822 result[index] = array[index];
1823 }
1824 while (++othIndex < othLength) {
1825 result[index++] = other[othIndex];
1826 }
1827 return result;
1828 }
1829
1830 /**
1831 * Copies the values of `source` to `array`.
1832 *
1833 * @private
1834 * @param {Array} source The array to copy values from.
1835 * @param {Array} [array=[]] The array to copy values to.
1836 * @returns {Array} Returns `array`.
1837 */
1838 function arrayCopy(source, array) {
1839 var index = -1,
1840 length = source.length;
1841
1842 array || (array = Array(length));
1843 while (++index < length) {
1844 array[index] = source[index];
1845 }
1846 return array;
1847 }
1848
1849 /**
1850 * A specialized version of `_.forEach` for arrays without support for callback
1851 * shorthands and `this` binding.
1852 *
1853 * @private
1854 * @param {Array} array The array to iterate over.
1855 * @param {Function} iteratee The function invoked per iteration.
1856 * @returns {Array} Returns `array`.
1857 */
1858 function arrayEach(array, iteratee) {
1859 var index = -1,
1860 length = array.length;
1861
1862 while (++index < length) {
1863 if (iteratee(array[index], index, array) === false) {
1864 break;
1865 }
1866 }
1867 return array;
1868 }
1869
1870 /**
1871 * A specialized version of `_.forEachRight` for arrays without support for
1872 * callback shorthands and `this` binding.
1873 *
1874 * @private
1875 * @param {Array} array The array to iterate over.
1876 * @param {Function} iteratee The function invoked per iteration.
1877 * @returns {Array} Returns `array`.
1878 */
1879 function arrayEachRight(array, iteratee) {
1880 var length = array.length;
1881
1882 while (length--) {
1883 if (iteratee(array[length], length, array) === false) {
1884 break;
1885 }
1886 }
1887 return array;
1888 }
1889
1890 /**
1891 * A specialized version of `_.every` for arrays without support for callback
1892 * shorthands and `this` binding.
1893 *
1894 * @private
1895 * @param {Array} array The array to iterate over.
1896 * @param {Function} predicate The function invoked per iteration.
1897 * @returns {boolean} Returns `true` if all elements pass the predicate check,
1898 * else `false`.
1899 */
1900 function arrayEvery(array, predicate) {
1901 var index = -1,
1902 length = array.length;
1903
1904 while (++index < length) {
1905 if (!predicate(array[index], index, array)) {
1906 return false;
1907 }
1908 }
1909 return true;
1910 }
1911
1912 /**
1913 * A specialized version of `baseExtremum` for arrays which invokes `iteratee`
1914 * with one argument: (value).
1915 *
1916 * @private
1917 * @param {Array} array The array to iterate over.
1918 * @param {Function} iteratee The function invoked per iteration.
1919 * @param {Function} comparator The function used to compare values.
1920 * @param {*} exValue The initial extremum value.
1921 * @returns {*} Returns the extremum value.
1922 */
1923 function arrayExtremum(array, iteratee, comparator, exValue) {
1924 var index = -1,
1925 length = array.length,
1926 computed = exValue,
1927 result = computed;
1928
1929 while (++index < length) {
1930 var value = array[index],
1931 current = +iteratee(value);
1932
1933 if (comparator(current, computed)) {
1934 computed = current;
1935 result = value;
1936 }
1937 }
1938 return result;
1939 }
1940
1941 /**
1942 * A specialized version of `_.filter` for arrays without support for callback
1943 * shorthands and `this` binding.
1944 *
1945 * @private
1946 * @param {Array} array The array to iterate over.
1947 * @param {Function} predicate The function invoked per iteration.
1948 * @returns {Array} Returns the new filtered array.
1949 */
1950 function arrayFilter(array, predicate) {
1951 var index = -1,
1952 length = array.length,
1953 resIndex = -1,
1954 result = [];
1955
1956 while (++index < length) {
1957 var value = array[index];
1958 if (predicate(value, index, array)) {
1959 result[++resIndex] = value;
1960 }
1961 }
1962 return result;
1963 }
1964
1965 /**
1966 * A specialized version of `_.map` for arrays without support for callback
1967 * shorthands and `this` binding.
1968 *
1969 * @private
1970 * @param {Array} array The array to iterate over.
1971 * @param {Function} iteratee The function invoked per iteration.
1972 * @returns {Array} Returns the new mapped array.
1973 */
1974 function arrayMap(array, iteratee) {
1975 var index = -1,
1976 length = array.length,
1977 result = Array(length);
1978
1979 while (++index < length) {
1980 result[index] = iteratee(array[index], index, array);
1981 }
1982 return result;
1983 }
1984
1985 /**
1986 * Appends the elements of `values` to `array`.
1987 *
1988 * @private
1989 * @param {Array} array The array to modify.
1990 * @param {Array} values The values to append.
1991 * @returns {Array} Returns `array`.
1992 */
1993 function arrayPush(array, values) {
1994 var index = -1,
1995 length = values.length,
1996 offset = array.length;
1997
1998 while (++index < length) {
1999 array[offset + index] = values[index];
2000 }
2001 return array;
2002 }
2003
2004 /**
2005 * A specialized version of `_.reduce` for arrays without support for callback
2006 * shorthands and `this` binding.
2007 *
2008 * @private
2009 * @param {Array} array The array to iterate over.
2010 * @param {Function} iteratee The function invoked per iteration.
2011 * @param {*} [accumulator] The initial value.
2012 * @param {boolean} [initFromArray] Specify using the first element of `array`
2013 * as the initial value.
2014 * @returns {*} Returns the accumulated value.
2015 */
2016 function arrayReduce(array, iteratee, accumulator, initFromArray) {
2017 var index = -1,
2018 length = array.length;
2019
2020 if (initFromArray && length) {
2021 accumulator = array[++index];
2022 }
2023 while (++index < length) {
2024 accumulator = iteratee(accumulator, array[index], index, array);
2025 }
2026 return accumulator;
2027 }
2028
2029 /**
2030 * A specialized version of `_.reduceRight` for arrays without support for
2031 * callback shorthands and `this` binding.
2032 *
2033 * @private
2034 * @param {Array} array The array to iterate over.
2035 * @param {Function} iteratee The function invoked per iteration.
2036 * @param {*} [accumulator] The initial value.
2037 * @param {boolean} [initFromArray] Specify using the last element of `array`
2038 * as the initial value.
2039 * @returns {*} Returns the accumulated value.
2040 */
2041 function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
2042 var length = array.length;
2043 if (initFromArray && length) {
2044 accumulator = array[--length];
2045 }
2046 while (length--) {
2047 accumulator = iteratee(accumulator, array[length], length, array);
2048 }
2049 return accumulator;
2050 }
2051
2052 /**
2053 * A specialized version of `_.some` for arrays without support for callback
2054 * shorthands and `this` binding.
2055 *
2056 * @private
2057 * @param {Array} array The array to iterate over.
2058 * @param {Function} predicate The function invoked per iteration.
2059 * @returns {boolean} Returns `true` if any element passes the predicate check,
2060 * else `false`.
2061 */
2062 function arraySome(array, predicate) {
2063 var index = -1,
2064 length = array.length;
2065
2066 while (++index < length) {
2067 if (predicate(array[index], index, array)) {
2068 return true;
2069 }
2070 }
2071 return false;
2072 }
2073
2074 /**
2075 * A specialized version of `_.sum` for arrays without support for callback
2076 * shorthands and `this` binding..
2077 *
2078 * @private
2079 * @param {Array} array The array to iterate over.
2080 * @param {Function} iteratee The function invoked per iteration.
2081 * @returns {number} Returns the sum.
2082 */
2083 function arraySum(array, iteratee) {
2084 var length = array.length,
2085 result = 0;
2086
2087 while (length--) {
2088 result += +iteratee(array[length]) || 0;
2089 }
2090 return result;
2091 }
2092
2093 /**
2094 * Used by `_.defaults` to customize its `_.assign` use.
2095 *
2096 * @private
2097 * @param {*} objectValue The destination object property value.
2098 * @param {*} sourceValue The source object property value.
2099 * @returns {*} Returns the value to assign to the destination object.
2100 */
2101 function assignDefaults(objectValue, sourceValue) {
2102 return objectValue === undefined ? sourceValue : objectValue;
2103 }
2104
2105 /**
2106 * Used by `_.template` to customize its `_.assign` use.
2107 *
2108 * **Note:** This function is like `assignDefaults` except that it ignores
2109 * inherited property values when checking if a property is `undefined`.
2110 *
2111 * @private
2112 * @param {*} objectValue The destination object property value.
2113 * @param {*} sourceValue The source object property value.
2114 * @param {string} key The key associated with the object and source values.
2115 * @param {Object} object The destination object.
2116 * @returns {*} Returns the value to assign to the destination object.
2117 */
2118 function assignOwnDefaults(objectValue, sourceValue, key, object) {
2119 return (objectValue === undefined || !hasOwnProperty.call(object, key))
2120 ? sourceValue
2121 : objectValue;
2122 }
2123
2124 /**
2125 * A specialized version of `_.assign` for customizing assigned values without
2126 * support for argument juggling, multiple sources, and `this` binding `customizer`
2127 * functions.
2128 *
2129 * @private
2130 * @param {Object} object The destination object.
2131 * @param {Object} source The source object.
2132 * @param {Function} customizer The function to customize assigned values.
2133 * @returns {Object} Returns `object`.
2134 */
2135 function assignWith(object, source, customizer) {
2136 var index = -1,
2137 props = keys(source),
2138 length = props.length;
2139
2140 while (++index < length) {
2141 var key = props[index],
2142 value = object[key],
2143 result = customizer(value, source[key], key, object, source);
2144
2145 if ((result === result ? (result !== value) : (value === value)) ||
2146 (value === undefined && !(key in object))) {
2147 object[key] = result;
2148 }
2149 }
2150 return object;
2151 }
2152
2153 /**
2154 * The base implementation of `_.assign` without support for argument juggling,
2155 * multiple sources, and `customizer` functions.
2156 *
2157 * @private
2158 * @param {Object} object The destination object.
2159 * @param {Object} source The source object.
2160 * @returns {Object} Returns `object`.
2161 */
2162 function baseAssign(object, source) {
2163 return source == null
2164 ? object
2165 : baseCopy(source, keys(source), object);
2166 }
2167
2168 /**
2169 * The base implementation of `_.at` without support for string collections
2170 * and individual key arguments.
2171 *
2172 * @private
2173 * @param {Array|Object} collection The collection to iterate over.
2174 * @param {number[]|string[]} props The property names or indexes of elements to pick.
2175 * @returns {Array} Returns the new array of picked elements.
2176 */
2177 function baseAt(collection, props) {
2178 var index = -1,
2179 isNil = collection == null,
2180 isArr = !isNil && isArrayLike(collection),
2181 length = isArr ? collection.length : 0,
2182 propsLength = props.length,
2183 result = Array(propsLength);
2184
2185 while(++index < propsLength) {
2186 var key = props[index];
2187 if (isArr) {
2188 result[index] = isIndex(key, length) ? collection[key] : undefined;
2189 } else {
2190 result[index] = isNil ? undefined : collection[key];
2191 }
2192 }
2193 return result;
2194 }
2195
2196 /**
2197 * Copies properties of `source` to `object`.
2198 *
2199 * @private
2200 * @param {Object} source The object to copy properties from.
2201 * @param {Array} props The property names to copy.
2202 * @param {Object} [object={}] The object to copy properties to.
2203 * @returns {Object} Returns `object`.
2204 */
2205 function baseCopy(source, props, object) {
2206 object || (object = {});
2207
2208 var index = -1,
2209 length = props.length;
2210
2211 while (++index < length) {
2212 var key = props[index];
2213 object[key] = source[key];
2214 }
2215 return object;
2216 }
2217
2218 /**
2219 * The base implementation of `_.callback` which supports specifying the
2220 * number of arguments to provide to `func`.
2221 *
2222 * @private
2223 * @param {*} [func=_.identity] The value to convert to a callback.
2224 * @param {*} [thisArg] The `this` binding of `func`.
2225 * @param {number} [argCount] The number of arguments to provide to `func`.
2226 * @returns {Function} Returns the callback.
2227 */
2228 function baseCallback(func, thisArg, argCount) {
2229 var type = typeof func;
2230 if (type == 'function') {
2231 return thisArg === undefined
2232 ? func
2233 : bindCallback(func, thisArg, argCount);
2234 }
2235 if (func == null) {
2236 return identity;
2237 }
2238 if (type == 'object') {
2239 return baseMatches(func);
2240 }
2241 return thisArg === undefined
2242 ? property(func)
2243 : baseMatchesProperty(func, thisArg);
2244 }
2245
2246 /**
2247 * The base implementation of `_.clone` without support for argument juggling
2248 * and `this` binding `customizer` functions.
2249 *
2250 * @private
2251 * @param {*} value The value to clone.
2252 * @param {boolean} [isDeep] Specify a deep clone.
2253 * @param {Function} [customizer] The function to customize cloning values.
2254 * @param {string} [key] The key of `value`.
2255 * @param {Object} [object] The object `value` belongs to.
2256 * @param {Array} [stackA=[]] Tracks traversed source objects.
2257 * @param {Array} [stackB=[]] Associates clones with source counterparts.
2258 * @returns {*} Returns the cloned value.
2259 */
2260 function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
2261 var result;
2262 if (customizer) {
2263 result = object ? customizer(value, key, object) : customizer(value);
2264 }
2265 if (result !== undefined) {
2266 return result;
2267 }
2268 if (!isObject(value)) {
2269 return value;
2270 }
2271 var isArr = isArray(value);
2272 if (isArr) {
2273 result = initCloneArray(value);
2274 if (!isDeep) {
2275 return arrayCopy(value, result);
2276 }
2277 } else {
2278 var tag = objToString.call(value),
2279 isFunc = tag == funcTag;
2280
2281 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
2282 result = initCloneObject(isFunc ? {} : value);
2283 if (!isDeep) {
2284 return baseAssign(result, value);
2285 }
2286 } else {
2287 return cloneableTags[tag]
2288 ? initCloneByTag(value, tag, isDeep)
2289 : (object ? value : {});
2290 }
2291 }
2292 // Check for circular references and return its corresponding clone.
2293 stackA || (stackA = []);
2294 stackB || (stackB = []);
2295
2296 var length = stackA.length;
2297 while (length--) {
2298 if (stackA[length] == value) {
2299 return stackB[length];
2300 }
2301 }
2302 // Add the source value to the stack of traversed objects and associate it with its clone.
2303 stackA.push(value);
2304 stackB.push(result);
2305
2306 // Recursively populate clone (susceptible to call stack limits).
2307 (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
2308 result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
2309 });
2310 return result;
2311 }
2312
2313 /**
2314 * The base implementation of `_.create` without support for assigning
2315 * properties to the created object.
2316 *
2317 * @private
2318 * @param {Object} prototype The object to inherit from.
2319 * @returns {Object} Returns the new object.
2320 */
2321 var baseCreate = (function() {
2322 function object() {}
2323 return function(prototype) {
2324 if (isObject(prototype)) {
2325 object.prototype = prototype;
2326 var result = new object;
2327 object.prototype = undefined;
2328 }
2329 return result || {};
2330 };
2331 }());
2332
2333 /**
2334 * The base implementation of `_.delay` and `_.defer` which accepts an index
2335 * of where to slice the arguments to provide to `func`.
2336 *
2337 * @private
2338 * @param {Function} func The function to delay.
2339 * @param {number} wait The number of milliseconds to delay invocation.
2340 * @param {Object} args The arguments provide to `func`.
2341 * @returns {number} Returns the timer id.
2342 */
2343 function baseDelay(func, wait, args) {
2344 if (typeof func != 'function') {
2345 throw new TypeError(FUNC_ERROR_TEXT);
2346 }
2347 return setTimeout(function() { func.apply(undefined, args); }, wait);
2348 }
2349
2350 /**
2351 * The base implementation of `_.difference` which accepts a single array
2352 * of values to exclude.
2353 *
2354 * @private
2355 * @param {Array} array The array to inspect.
2356 * @param {Array} values The values to exclude.
2357 * @returns {Array} Returns the new array of filtered values.
2358 */
2359 function baseDifference(array, values) {
2360 var length = array ? array.length : 0,
2361 result = [];
2362
2363 if (!length) {
2364 return result;
2365 }
2366 var index = -1,
2367 indexOf = getIndexOf(),
2368 isCommon = indexOf == baseIndexOf,
2369 cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null,
2370 valuesLength = values.length;
2371
2372 if (cache) {
2373 indexOf = cacheIndexOf;
2374 isCommon = false;
2375 values = cache;
2376 }
2377 outer:
2378 while (++index < length) {
2379 var value = array[index];
2380
2381 if (isCommon && value === value) {
2382 var valuesIndex = valuesLength;
2383 while (valuesIndex--) {
2384 if (values[valuesIndex] === value) {
2385 continue outer;
2386 }
2387 }
2388 result.push(value);
2389 }
2390 else if (indexOf(values, value, 0) < 0) {
2391 result.push(value);
2392 }
2393 }
2394 return result;
2395 }
2396
2397 /**
2398 * The base implementation of `_.forEach` without support for callback
2399 * shorthands and `this` binding.
2400 *
2401 * @private
2402 * @param {Array|Object|string} collection The collection to iterate over.
2403 * @param {Function} iteratee The function invoked per iteration.
2404 * @returns {Array|Object|string} Returns `collection`.
2405 */
2406 var baseEach = createBaseEach(baseForOwn);
2407
2408 /**
2409 * The base implementation of `_.forEachRight` without support for callback
2410 * shorthands and `this` binding.
2411 *
2412 * @private
2413 * @param {Array|Object|string} collection The collection to iterate over.
2414 * @param {Function} iteratee The function invoked per iteration.
2415 * @returns {Array|Object|string} Returns `collection`.
2416 */
2417 var baseEachRight = createBaseEach(baseForOwnRight, true);
2418
2419 /**
2420 * The base implementation of `_.every` without support for callback
2421 * shorthands and `this` binding.
2422 *
2423 * @private
2424 * @param {Array|Object|string} collection The collection to iterate over.
2425 * @param {Function} predicate The function invoked per iteration.
2426 * @returns {boolean} Returns `true` if all elements pass the predicate check,
2427 * else `false`
2428 */
2429 function baseEvery(collection, predicate) {
2430 var result = true;
2431 baseEach(collection, function(value, index, collection) {
2432 result = !!predicate(value, index, collection);
2433 return result;
2434 });
2435 return result;
2436 }
2437
2438 /**
2439 * Gets the extremum value of `collection` invoking `iteratee` for each value
2440 * in `collection` to generate the criterion by which the value is ranked.
2441 * The `iteratee` is invoked with three arguments: (value, index|key, collection).
2442 *
2443 * @private
2444 * @param {Array|Object|string} collection The collection to iterate over.
2445 * @param {Function} iteratee The function invoked per iteration.
2446 * @param {Function} comparator The function used to compare values.
2447 * @param {*} exValue The initial extremum value.
2448 * @returns {*} Returns the extremum value.
2449 */
2450 function baseExtremum(collection, iteratee, comparator, exValue) {
2451 var computed = exValue,
2452 result = computed;
2453
2454 baseEach(collection, function(value, index, collection) {
2455 var current = +iteratee(value, index, collection);
2456 if (comparator(current, computed) || (current === exValue && current === result)) {
2457 computed = current;
2458 result = value;
2459 }
2460 });
2461 return result;
2462 }
2463
2464 /**
2465 * The base implementation of `_.fill` without an iteratee call guard.
2466 *
2467 * @private
2468 * @param {Array} array The array to fill.
2469 * @param {*} value The value to fill `array` with.
2470 * @param {number} [start=0] The start position.
2471 * @param {number} [end=array.length] The end position.
2472 * @returns {Array} Returns `array`.
2473 */
2474 function baseFill(array, value, start, end) {
2475 var length = array.length;
2476
2477 start = start == null ? 0 : (+start || 0);
2478 if (start < 0) {
2479 start = -start > length ? 0 : (length + start);
2480 }
2481 end = (end === undefined || end > length) ? length : (+end || 0);
2482 if (end < 0) {
2483 end += length;
2484 }
2485 length = start > end ? 0 : (end >>> 0);
2486 start >>>= 0;
2487
2488 while (start < length) {
2489 array[start++] = value;
2490 }
2491 return array;
2492 }
2493
2494 /**
2495 * The base implementation of `_.filter` without support for callback
2496 * shorthands and `this` binding.
2497 *
2498 * @private
2499 * @param {Array|Object|string} collection The collection to iterate over.
2500 * @param {Function} predicate The function invoked per iteration.
2501 * @returns {Array} Returns the new filtered array.
2502 */
2503 function baseFilter(collection, predicate) {
2504 var result = [];
2505 baseEach(collection, function(value, index, collection) {
2506 if (predicate(value, index, collection)) {
2507 result.push(value);
2508 }
2509 });
2510 return result;
2511 }
2512
2513 /**
2514 * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
2515 * without support for callback shorthands and `this` binding, which iterates
2516 * over `collection` using the provided `eachFunc`.
2517 *
2518 * @private
2519 * @param {Array|Object|string} collection The collection to search.
2520 * @param {Function} predicate The function invoked per iteration.
2521 * @param {Function} eachFunc The function to iterate over `collection`.
2522 * @param {boolean} [retKey] Specify returning the key of the found element
2523 * instead of the element itself.
2524 * @returns {*} Returns the found element or its key, else `undefined`.
2525 */
2526 function baseFind(collection, predicate, eachFunc, retKey) {
2527 var result;
2528 eachFunc(collection, function(value, key, collection) {
2529 if (predicate(value, key, collection)) {
2530 result = retKey ? key : value;
2531 return false;
2532 }
2533 });
2534 return result;
2535 }
2536
2537 /**
2538 * The base implementation of `_.flatten` with added support for restricting
2539 * flattening and specifying the start index.
2540 *
2541 * @private
2542 * @param {Array} array The array to flatten.
2543 * @param {boolean} [isDeep] Specify a deep flatten.
2544 * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
2545 * @param {Array} [result=[]] The initial result value.
2546 * @returns {Array} Returns the new flattened array.
2547 */
2548 function baseFlatten(array, isDeep, isStrict, result) {
2549 result || (result = []);
2550
2551 var index = -1,
2552 length = array.length;
2553
2554 while (++index < length) {
2555 var value = array[index];
2556 if (isObjectLike(value) && isArrayLike(value) &&
2557 (isStrict || isArray(value) || isArguments(value))) {
2558 if (isDeep) {
2559 // Recursively flatten arrays (susceptible to call stack limits).
2560 baseFlatten(value, isDeep, isStrict, result);
2561 } else {
2562 arrayPush(result, value);
2563 }
2564 } else if (!isStrict) {
2565 result[result.length] = value;
2566 }
2567 }
2568 return result;
2569 }
2570
2571 /**
2572 * The base implementation of `baseForIn` and `baseForOwn` which iterates
2573 * over `object` properties returned by `keysFunc` invoking `iteratee` for
2574 * each property. Iteratee functions may exit iteration early by explicitly
2575 * returning `false`.
2576 *
2577 * @private
2578 * @param {Object} object The object to iterate over.
2579 * @param {Function} iteratee The function invoked per iteration.
2580 * @param {Function} keysFunc The function to get the keys of `object`.
2581 * @returns {Object} Returns `object`.
2582 */
2583 var baseFor = createBaseFor();
2584
2585 /**
2586 * This function is like `baseFor` except that it iterates over properties
2587 * in the opposite order.
2588 *
2589 * @private
2590 * @param {Object} object The object to iterate over.
2591 * @param {Function} iteratee The function invoked per iteration.
2592 * @param {Function} keysFunc The function to get the keys of `object`.
2593 * @returns {Object} Returns `object`.
2594 */
2595 var baseForRight = createBaseFor(true);
2596
2597 /**
2598 * The base implementation of `_.forIn` without support for callback
2599 * shorthands and `this` binding.
2600 *
2601 * @private
2602 * @param {Object} object The object to iterate over.
2603 * @param {Function} iteratee The function invoked per iteration.
2604 * @returns {Object} Returns `object`.
2605 */
2606 function baseForIn(object, iteratee) {
2607 return baseFor(object, iteratee, keysIn);
2608 }
2609
2610 /**
2611 * The base implementation of `_.forOwn` without support for callback
2612 * shorthands and `this` binding.
2613 *
2614 * @private
2615 * @param {Object} object The object to iterate over.
2616 * @param {Function} iteratee The function invoked per iteration.
2617 * @returns {Object} Returns `object`.
2618 */
2619 function baseForOwn(object, iteratee) {
2620 return baseFor(object, iteratee, keys);
2621 }
2622
2623 /**
2624 * The base implementation of `_.forOwnRight` without support for callback
2625 * shorthands and `this` binding.
2626 *
2627 * @private
2628 * @param {Object} object The object to iterate over.
2629 * @param {Function} iteratee The function invoked per iteration.
2630 * @returns {Object} Returns `object`.
2631 */
2632 function baseForOwnRight(object, iteratee) {
2633 return baseForRight(object, iteratee, keys);
2634 }
2635
2636 /**
2637 * The base implementation of `_.functions` which creates an array of
2638 * `object` function property names filtered from those provided.
2639 *
2640 * @private
2641 * @param {Object} object The object to inspect.
2642 * @param {Array} props The property names to filter.
2643 * @returns {Array} Returns the new array of filtered property names.
2644 */
2645 function baseFunctions(object, props) {
2646 var index = -1,
2647 length = props.length,
2648 resIndex = -1,
2649 result = [];
2650
2651 while (++index < length) {
2652 var key = props[index];
2653 if (isFunction(object[key])) {
2654 result[++resIndex] = key;
2655 }
2656 }
2657 return result;
2658 }
2659
2660 /**
2661 * The base implementation of `get` without support for string paths
2662 * and default values.
2663 *
2664 * @private
2665 * @param {Object} object The object to query.
2666 * @param {Array} path The path of the property to get.
2667 * @param {string} [pathKey] The key representation of path.
2668 * @returns {*} Returns the resolved value.
2669 */
2670 function baseGet(object, path, pathKey) {
2671 if (object == null) {
2672 return;
2673 }
2674 if (pathKey !== undefined && pathKey in toObject(object)) {
2675 path = [pathKey];
2676 }
2677 var index = 0,
2678 length = path.length;
2679
2680 while (object != null && index < length) {
2681 object = object[path[index++]];
2682 }
2683 return (index && index == length) ? object : undefined;
2684 }
2685
2686 /**
2687 * The base implementation of `_.isEqual` without support for `this` binding
2688 * `customizer` functions.
2689 *
2690 * @private
2691 * @param {*} value The value to compare.
2692 * @param {*} other The other value to compare.
2693 * @param {Function} [customizer] The function to customize comparing values.
2694 * @param {boolean} [isLoose] Specify performing partial comparisons.
2695 * @param {Array} [stackA] Tracks traversed `value` objects.
2696 * @param {Array} [stackB] Tracks traversed `other` objects.
2697 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
2698 */
2699 function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
2700 if (value === other) {
2701 return true;
2702 }
2703 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
2704 return value !== value && other !== other;
2705 }
2706 return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
2707 }
2708
2709 /**
2710 * A specialized version of `baseIsEqual` for arrays and objects which performs
2711 * deep comparisons and tracks traversed objects enabling objects with circular
2712 * references to be compared.
2713 *
2714 * @private
2715 * @param {Object} object The object to compare.
2716 * @param {Object} other The other object to compare.
2717 * @param {Function} equalFunc The function to determine equivalents of values.
2718 * @param {Function} [customizer] The function to customize comparing objects.
2719 * @param {boolean} [isLoose] Specify performing partial comparisons.
2720 * @param {Array} [stackA=[]] Tracks traversed `value` objects.
2721 * @param {Array} [stackB=[]] Tracks traversed `other` objects.
2722 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
2723 */
2724 function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
2725 var objIsArr = isArray(object),
2726 othIsArr = isArray(other),
2727 objTag = arrayTag,
2728 othTag = arrayTag;
2729
2730 if (!objIsArr) {
2731 objTag = objToString.call(object);
2732 if (objTag == argsTag) {
2733 objTag = objectTag;
2734 } else if (objTag != objectTag) {
2735 objIsArr = isTypedArray(object);
2736 }
2737 }
2738 if (!othIsArr) {
2739 othTag = objToString.call(other);
2740 if (othTag == argsTag) {
2741 othTag = objectTag;
2742 } else if (othTag != objectTag) {
2743 othIsArr = isTypedArray(other);
2744 }
2745 }
2746 var objIsObj = objTag == objectTag,
2747 othIsObj = othTag == objectTag,
2748 isSameTag = objTag == othTag;
2749
2750 if (isSameTag && !(objIsArr || objIsObj)) {
2751 return equalByTag(object, other, objTag);
2752 }
2753 if (!isLoose) {
2754 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
2755 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
2756
2757 if (objIsWrapped || othIsWrapped) {
2758 return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
2759 }
2760 }
2761 if (!isSameTag) {
2762 return false;
2763 }
2764 // Assume cyclic values are equal.
2765 // For more information on detecting circular references see https://es5.github.io/#JO.
2766 stackA || (stackA = []);
2767 stackB || (stackB = []);
2768
2769 var length = stackA.length;
2770 while (length--) {
2771 if (stackA[length] == object) {
2772 return stackB[length] == other;
2773 }
2774 }
2775 // Add `object` and `other` to the stack of traversed objects.
2776 stackA.push(object);
2777 stackB.push(other);
2778
2779 var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
2780
2781 stackA.pop();
2782 stackB.pop();
2783
2784 return result;
2785 }
2786
2787 /**
2788 * The base implementation of `_.isMatch` without support for callback
2789 * shorthands and `this` binding.
2790 *
2791 * @private
2792 * @param {Object} object The object to inspect.
2793 * @param {Array} matchData The propery names, values, and compare flags to match.
2794 * @param {Function} [customizer] The function to customize comparing objects.
2795 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
2796 */
2797 function baseIsMatch(object, matchData, customizer) {
2798 var index = matchData.length,
2799 length = index,
2800 noCustomizer = !customizer;
2801
2802 if (object == null) {
2803 return !length;
2804 }
2805 object = toObject(object);
2806 while (index--) {
2807 var data = matchData[index];
2808 if ((noCustomizer && data[2])
2809 ? data[1] !== object[data[0]]
2810 : !(data[0] in object)
2811 ) {
2812 return false;
2813 }
2814 }
2815 while (++index < length) {
2816 data = matchData[index];
2817 var key = data[0],
2818 objValue = object[key],
2819 srcValue = data[1];
2820
2821 if (noCustomizer && data[2]) {
2822 if (objValue === undefined && !(key in object)) {
2823 return false;
2824 }
2825 } else {
2826 var result = customizer ? customizer(objValue, srcValue, key) : undefined;
2827 if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
2828 return false;
2829 }
2830 }
2831 }
2832 return true;
2833 }
2834
2835 /**
2836 * The base implementation of `_.map` without support for callback shorthands
2837 * and `this` binding.
2838 *
2839 * @private
2840 * @param {Array|Object|string} collection The collection to iterate over.
2841 * @param {Function} iteratee The function invoked per iteration.
2842 * @returns {Array} Returns the new mapped array.
2843 */
2844 function baseMap(collection, iteratee) {
2845 var index = -1,
2846 result = isArrayLike(collection) ? Array(collection.length) : [];
2847
2848 baseEach(collection, function(value, key, collection) {
2849 result[++index] = iteratee(value, key, collection);
2850 });
2851 return result;
2852 }
2853
2854 /**
2855 * The base implementation of `_.matches` which does not clone `source`.
2856 *
2857 * @private
2858 * @param {Object} source The object of property values to match.
2859 * @returns {Function} Returns the new function.
2860 */
2861 function baseMatches(source) {
2862 var matchData = getMatchData(source);
2863 if (matchData.length == 1 && matchData[0][2]) {
2864 var key = matchData[0][0],
2865 value = matchData[0][1];
2866
2867 return function(object) {
2868 if (object == null) {
2869 return false;
2870 }
2871 return object[key] === value && (value !== undefined || (key in toObject(object)));
2872 };
2873 }
2874 return function(object) {
2875 return baseIsMatch(object, matchData);
2876 };
2877 }
2878
2879 /**
2880 * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
2881 *
2882 * @private
2883 * @param {string} path The path of the property to get.
2884 * @param {*} srcValue The value to compare.
2885 * @returns {Function} Returns the new function.
2886 */
2887 function baseMatchesProperty(path, srcValue) {
2888 var isArr = isArray(path),
2889 isCommon = isKey(path) && isStrictComparable(srcValue),
2890 pathKey = (path + '');
2891
2892 path = toPath(path);
2893 return function(object) {
2894 if (object == null) {
2895 return false;
2896 }
2897 var key = pathKey;
2898 object = toObject(object);
2899 if ((isArr || !isCommon) && !(key in object)) {
2900 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
2901 if (object == null) {
2902 return false;
2903 }
2904 key = last(path);
2905 object = toObject(object);
2906 }
2907 return object[key] === srcValue
2908 ? (srcValue !== undefined || (key in object))
2909 : baseIsEqual(srcValue, object[key], undefined, true);
2910 };
2911 }
2912
2913 /**
2914 * The base implementation of `_.merge` without support for argument juggling,
2915 * multiple sources, and `this` binding `customizer` functions.
2916 *
2917 * @private
2918 * @param {Object} object The destination object.
2919 * @param {Object} source The source object.
2920 * @param {Function} [customizer] The function to customize merged values.
2921 * @param {Array} [stackA=[]] Tracks traversed source objects.
2922 * @param {Array} [stackB=[]] Associates values with source counterparts.
2923 * @returns {Object} Returns `object`.
2924 */
2925 function baseMerge(object, source, customizer, stackA, stackB) {
2926 if (!isObject(object)) {
2927 return object;
2928 }
2929 var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
2930 props = isSrcArr ? undefined : keys(source);
2931
2932 arrayEach(props || source, function(srcValue, key) {
2933 if (props) {
2934 key = srcValue;
2935 srcValue = source[key];
2936 }
2937 if (isObjectLike(srcValue)) {
2938 stackA || (stackA = []);
2939 stackB || (stackB = []);
2940 baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
2941 }
2942 else {
2943 var value = object[key],
2944 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
2945 isCommon = result === undefined;
2946
2947 if (isCommon) {
2948 result = srcValue;
2949 }
2950 if ((result !== undefined || (isSrcArr && !(key in object))) &&
2951 (isCommon || (result === result ? (result !== value) : (value === value)))) {
2952 object[key] = result;
2953 }
2954 }
2955 });
2956 return object;
2957 }
2958
2959 /**
2960 * A specialized version of `baseMerge` for arrays and objects which performs
2961 * deep merges and tracks traversed objects enabling objects with circular
2962 * references to be merged.
2963 *
2964 * @private
2965 * @param {Object} object The destination object.
2966 * @param {Object} source The source object.
2967 * @param {string} key The key of the value to merge.
2968 * @param {Function} mergeFunc The function to merge values.
2969 * @param {Function} [customizer] The function to customize merged values.
2970 * @param {Array} [stackA=[]] Tracks traversed source objects.
2971 * @param {Array} [stackB=[]] Associates values with source counterparts.
2972 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
2973 */
2974 function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
2975 var length = stackA.length,
2976 srcValue = source[key];
2977
2978 while (length--) {
2979 if (stackA[length] == srcValue) {
2980 object[key] = stackB[length];
2981 return;
2982 }
2983 }
2984 var value = object[key],
2985 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
2986 isCommon = result === undefined;
2987
2988 if (isCommon) {
2989 result = srcValue;
2990 if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
2991 result = isArray(value)
2992 ? value
2993 : (isArrayLike(value) ? arrayCopy(value) : []);
2994 }
2995 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
2996 result = isArguments(value)
2997 ? toPlainObject(value)
2998 : (isPlainObject(value) ? value : {});
2999 }
3000 else {
3001 isCommon = false;
3002 }
3003 }
3004 // Add the source value to the stack of traversed objects and associate
3005 // it with its merged value.
3006 stackA.push(srcValue);
3007 stackB.push(result);
3008
3009 if (isCommon) {
3010 // Recursively merge objects and arrays (susceptible to call stack limits).
3011 object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
3012 } else if (result === result ? (result !== value) : (value === value)) {
3013 object[key] = result;
3014 }
3015 }
3016
3017 /**
3018 * The base implementation of `_.property` without support for deep paths.
3019 *
3020 * @private
3021 * @param {string} key The key of the property to get.
3022 * @returns {Function} Returns the new function.
3023 */
3024 function baseProperty(key) {
3025 return function(object) {
3026 return object == null ? undefined : object[key];
3027 };
3028 }
3029
3030 /**
3031 * A specialized version of `baseProperty` which supports deep paths.
3032 *
3033 * @private
3034 * @param {Array|string} path The path of the property to get.
3035 * @returns {Function} Returns the new function.
3036 */
3037 function basePropertyDeep(path) {
3038 var pathKey = (path + '');
3039 path = toPath(path);
3040 return function(object) {
3041 return baseGet(object, path, pathKey);
3042 };
3043 }
3044
3045 /**
3046 * The base implementation of `_.pullAt` without support for individual
3047 * index arguments and capturing the removed elements.
3048 *
3049 * @private
3050 * @param {Array} array The array to modify.
3051 * @param {number[]} indexes The indexes of elements to remove.
3052 * @returns {Array} Returns `array`.
3053 */
3054 function basePullAt(array, indexes) {
3055 var length = array ? indexes.length : 0;
3056 while (length--) {
3057 var index = indexes[length];
3058 if (index != previous && isIndex(index)) {
3059 var previous = index;
3060 splice.call(array, index, 1);
3061 }
3062 }
3063 return array;
3064 }
3065
3066 /**
3067 * The base implementation of `_.random` without support for argument juggling
3068 * and returning floating-point numbers.
3069 *
3070 * @private
3071 * @param {number} min The minimum possible value.
3072 * @param {number} max The maximum possible value.
3073 * @returns {number} Returns the random number.
3074 */
3075 function baseRandom(min, max) {
3076 return min + nativeFloor(nativeRandom() * (max - min + 1));
3077 }
3078
3079 /**
3080 * The base implementation of `_.reduce` and `_.reduceRight` without support
3081 * for callback shorthands and `this` binding, which iterates over `collection`
3082 * using the provided `eachFunc`.
3083 *
3084 * @private
3085 * @param {Array|Object|string} collection The collection to iterate over.
3086 * @param {Function} iteratee The function invoked per iteration.
3087 * @param {*} accumulator The initial value.
3088 * @param {boolean} initFromCollection Specify using the first or last element
3089 * of `collection` as the initial value.
3090 * @param {Function} eachFunc The function to iterate over `collection`.
3091 * @returns {*} Returns the accumulated value.
3092 */
3093 function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
3094 eachFunc(collection, function(value, index, collection) {
3095 accumulator = initFromCollection
3096 ? (initFromCollection = false, value)
3097 : iteratee(accumulator, value, index, collection);
3098 });
3099 return accumulator;
3100 }
3101
3102 /**
3103 * The base implementation of `setData` without support for hot loop detection.
3104 *
3105 * @private
3106 * @param {Function} func The function to associate metadata with.
3107 * @param {*} data The metadata.
3108 * @returns {Function} Returns `func`.
3109 */
3110 var baseSetData = !metaMap ? identity : function(func, data) {
3111 metaMap.set(func, data);
3112 return func;
3113 };
3114
3115 /**
3116 * The base implementation of `_.slice` without an iteratee call guard.
3117 *
3118 * @private
3119 * @param {Array} array The array to slice.
3120 * @param {number} [start=0] The start position.
3121 * @param {number} [end=array.length] The end position.
3122 * @returns {Array} Returns the slice of `array`.
3123 */
3124 function baseSlice(array, start, end) {
3125 var index = -1,
3126 length = array.length;
3127
3128 start = start == null ? 0 : (+start || 0);
3129 if (start < 0) {
3130 start = -start > length ? 0 : (length + start);
3131 }
3132 end = (end === undefined || end > length) ? length : (+end || 0);
3133 if (end < 0) {
3134 end += length;
3135 }
3136 length = start > end ? 0 : ((end - start) >>> 0);
3137 start >>>= 0;
3138
3139 var result = Array(length);
3140 while (++index < length) {
3141 result[index] = array[index + start];
3142 }
3143 return result;
3144 }
3145
3146 /**
3147 * The base implementation of `_.some` without support for callback shorthands
3148 * and `this` binding.
3149 *
3150 * @private
3151 * @param {Array|Object|string} collection The collection to iterate over.
3152 * @param {Function} predicate The function invoked per iteration.
3153 * @returns {boolean} Returns `true` if any element passes the predicate check,
3154 * else `false`.
3155 */
3156 function baseSome(collection, predicate) {
3157 var result;
3158
3159 baseEach(collection, function(value, index, collection) {
3160 result = predicate(value, index, collection);
3161 return !result;
3162 });
3163 return !!result;
3164 }
3165
3166 /**
3167 * The base implementation of `_.sortBy` which uses `comparer` to define
3168 * the sort order of `array` and replaces criteria objects with their
3169 * corresponding values.
3170 *
3171 * @private
3172 * @param {Array} array The array to sort.
3173 * @param {Function} comparer The function to define sort order.
3174 * @returns {Array} Returns `array`.
3175 */
3176 function baseSortBy(array, comparer) {
3177 var length = array.length;
3178
3179 array.sort(comparer);
3180 while (length--) {
3181 array[length] = array[length].value;
3182 }
3183 return array;
3184 }
3185
3186 /**
3187 * The base implementation of `_.sortByOrder` without param guards.
3188 *
3189 * @private
3190 * @param {Array|Object|string} collection The collection to iterate over.
3191 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
3192 * @param {boolean[]} orders The sort orders of `iteratees`.
3193 * @returns {Array} Returns the new sorted array.
3194 */
3195 function baseSortByOrder(collection, iteratees, orders) {
3196 var callback = getCallback(),
3197 index = -1;
3198
3199 iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); });
3200
3201 var result = baseMap(collection, function(value) {
3202 var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); });
3203 return { 'criteria': criteria, 'index': ++index, 'value': value };
3204 });
3205
3206 return baseSortBy(result, function(object, other) {
3207 return compareMultiple(object, other, orders);
3208 });
3209 }
3210
3211 /**
3212 * The base implementation of `_.sum` without support for callback shorthands
3213 * and `this` binding.
3214 *
3215 * @private
3216 * @param {Array|Object|string} collection The collection to iterate over.
3217 * @param {Function} iteratee The function invoked per iteration.
3218 * @returns {number} Returns the sum.
3219 */
3220 function baseSum(collection, iteratee) {
3221 var result = 0;
3222 baseEach(collection, function(value, index, collection) {
3223 result += +iteratee(value, index, collection) || 0;
3224 });
3225 return result;
3226 }
3227
3228 /**
3229 * The base implementation of `_.uniq` without support for callback shorthands
3230 * and `this` binding.
3231 *
3232 * @private
3233 * @param {Array} array The array to inspect.
3234 * @param {Function} [iteratee] The function invoked per iteration.
3235 * @returns {Array} Returns the new duplicate-value-free array.
3236 */
3237 function baseUniq(array, iteratee) {
3238 var index = -1,
3239 indexOf = getIndexOf(),
3240 length = array.length,
3241 isCommon = indexOf == baseIndexOf,
3242 isLarge = isCommon && length >= LARGE_ARRAY_SIZE,
3243 seen = isLarge ? createCache() : null,
3244 result = [];
3245
3246 if (seen) {
3247 indexOf = cacheIndexOf;
3248 isCommon = false;
3249 } else {
3250 isLarge = false;
3251 seen = iteratee ? [] : result;
3252 }
3253 outer:
3254 while (++index < length) {
3255 var value = array[index],
3256 computed = iteratee ? iteratee(value, index, array) : value;
3257
3258 if (isCommon && value === value) {
3259 var seenIndex = seen.length;
3260 while (seenIndex--) {
3261 if (seen[seenIndex] === computed) {
3262 continue outer;
3263 }
3264 }
3265 if (iteratee) {
3266 seen.push(computed);
3267 }
3268 result.push(value);
3269 }
3270 else if (indexOf(seen, computed, 0) < 0) {
3271 if (iteratee || isLarge) {
3272 seen.push(computed);
3273 }
3274 result.push(value);
3275 }
3276 }
3277 return result;
3278 }
3279
3280 /**
3281 * The base implementation of `_.values` and `_.valuesIn` which creates an
3282 * array of `object` property values corresponding to the property names
3283 * of `props`.
3284 *
3285 * @private
3286 * @param {Object} object The object to query.
3287 * @param {Array} props The property names to get values for.
3288 * @returns {Object} Returns the array of property values.
3289 */
3290 function baseValues(object, props) {
3291 var index = -1,
3292 length = props.length,
3293 result = Array(length);
3294
3295 while (++index < length) {
3296 result[index] = object[props[index]];
3297 }
3298 return result;
3299 }
3300
3301 /**
3302 * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
3303 * and `_.takeWhile` without support for callback shorthands and `this` binding.
3304 *
3305 * @private
3306 * @param {Array} array The array to query.
3307 * @param {Function} predicate The function invoked per iteration.
3308 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
3309 * @param {boolean} [fromRight] Specify iterating from right to left.
3310 * @returns {Array} Returns the slice of `array`.
3311 */
3312 function baseWhile(array, predicate, isDrop, fromRight) {
3313 var length = array.length,
3314 index = fromRight ? length : -1;
3315
3316 while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
3317 return isDrop
3318 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
3319 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
3320 }
3321
3322 /**
3323 * The base implementation of `wrapperValue` which returns the result of
3324 * performing a sequence of actions on the unwrapped `value`, where each
3325 * successive action is supplied the return value of the previous.
3326 *
3327 * @private
3328 * @param {*} value The unwrapped value.
3329 * @param {Array} actions Actions to peform to resolve the unwrapped value.
3330 * @returns {*} Returns the resolved value.
3331 */
3332 function baseWrapperValue(value, actions) {
3333 var result = value;
3334 if (result instanceof LazyWrapper) {
3335 result = result.value();
3336 }
3337 var index = -1,
3338 length = actions.length;
3339
3340 while (++index < length) {
3341 var action = actions[index];
3342 result = action.func.apply(action.thisArg, arrayPush([result], action.args));
3343 }
3344 return result;
3345 }
3346
3347 /**
3348 * Performs a binary search of `array` to determine the index at which `value`
3349 * should be inserted into `array` in order to maintain its sort order.
3350 *
3351 * @private
3352 * @param {Array} array The sorted array to inspect.
3353 * @param {*} value The value to evaluate.
3354 * @param {boolean} [retHighest] Specify returning the highest qualified index.
3355 * @returns {number} Returns the index at which `value` should be inserted
3356 * into `array`.
3357 */
3358 function binaryIndex(array, value, retHighest) {
3359 var low = 0,
3360 high = array ? array.length : low;
3361
3362 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
3363 while (low < high) {
3364 var mid = (low + high) >>> 1,
3365 computed = array[mid];
3366
3367 if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
3368 low = mid + 1;
3369 } else {
3370 high = mid;
3371 }
3372 }
3373 return high;
3374 }
3375 return binaryIndexBy(array, value, identity, retHighest);
3376 }
3377
3378 /**
3379 * This function is like `binaryIndex` except that it invokes `iteratee` for
3380 * `value` and each element of `array` to compute their sort ranking. The
3381 * iteratee is invoked with one argument; (value).
3382 *
3383 * @private
3384 * @param {Array} array The sorted array to inspect.
3385 * @param {*} value The value to evaluate.
3386 * @param {Function} iteratee The function invoked per iteration.
3387 * @param {boolean} [retHighest] Specify returning the highest qualified index.
3388 * @returns {number} Returns the index at which `value` should be inserted
3389 * into `array`.
3390 */
3391 function binaryIndexBy(array, value, iteratee, retHighest) {
3392 value = iteratee(value);
3393
3394 var low = 0,
3395 high = array ? array.length : 0,
3396 valIsNaN = value !== value,
3397 valIsNull = value === null,
3398 valIsUndef = value === undefined;
3399
3400 while (low < high) {
3401 var mid = nativeFloor((low + high) / 2),
3402 computed = iteratee(array[mid]),
3403 isDef = computed !== undefined,
3404 isReflexive = computed === computed;
3405
3406 if (valIsNaN) {
3407 var setLow = isReflexive || retHighest;
3408 } else if (valIsNull) {
3409 setLow = isReflexive && isDef && (retHighest || computed != null);
3410 } else if (valIsUndef) {
3411 setLow = isReflexive && (retHighest || isDef);
3412 } else if (computed == null) {
3413 setLow = false;
3414 } else {
3415 setLow = retHighest ? (computed <= value) : (computed < value);
3416 }
3417 if (setLow) {
3418 low = mid + 1;
3419 } else {
3420 high = mid;
3421 }
3422 }
3423 return nativeMin(high, MAX_ARRAY_INDEX);
3424 }
3425
3426 /**
3427 * A specialized version of `baseCallback` which only supports `this` binding
3428 * and specifying the number of arguments to provide to `func`.
3429 *
3430 * @private
3431 * @param {Function} func The function to bind.
3432 * @param {*} thisArg The `this` binding of `func`.
3433 * @param {number} [argCount] The number of arguments to provide to `func`.
3434 * @returns {Function} Returns the callback.
3435 */
3436 function bindCallback(func, thisArg, argCount) {
3437 if (typeof func != 'function') {
3438 return identity;
3439 }
3440 if (thisArg === undefined) {
3441 return func;
3442 }
3443 switch (argCount) {
3444 case 1: return function(value) {
3445 return func.call(thisArg, value);
3446 };
3447 case 3: return function(value, index, collection) {
3448 return func.call(thisArg, value, index, collection);
3449 };
3450 case 4: return function(accumulator, value, index, collection) {
3451 return func.call(thisArg, accumulator, value, index, collection);
3452 };
3453 case 5: return function(value, other, key, object, source) {
3454 return func.call(thisArg, value, other, key, object, source);
3455 };
3456 }
3457 return function() {
3458 return func.apply(thisArg, arguments);
3459 };
3460 }
3461
3462 /**
3463 * Creates a clone of the given array buffer.
3464 *
3465 * @private
3466 * @param {ArrayBuffer} buffer The array buffer to clone.
3467 * @returns {ArrayBuffer} Returns the cloned array buffer.
3468 */
3469 function bufferClone(buffer) {
3470 var result = new ArrayBuffer(buffer.byteLength),
3471 view = new Uint8Array(result);
3472
3473 view.set(new Uint8Array(buffer));
3474 return result;
3475 }
3476
3477 /**
3478 * Creates an array that is the composition of partially applied arguments,
3479 * placeholders, and provided arguments into a single array of arguments.
3480 *
3481 * @private
3482 * @param {Array|Object} args The provided arguments.
3483 * @param {Array} partials The arguments to prepend to those provided.
3484 * @param {Array} holders The `partials` placeholder indexes.
3485 * @returns {Array} Returns the new array of composed arguments.
3486 */
3487 function composeArgs(args, partials, holders) {
3488 var holdersLength = holders.length,
3489 argsIndex = -1,
3490 argsLength = nativeMax(args.length - holdersLength, 0),
3491 leftIndex = -1,
3492 leftLength = partials.length,
3493 result = Array(leftLength + argsLength);
3494
3495 while (++leftIndex < leftLength) {
3496 result[leftIndex] = partials[leftIndex];
3497 }
3498 while (++argsIndex < holdersLength) {
3499 result[holders[argsIndex]] = args[argsIndex];
3500 }
3501 while (argsLength--) {
3502 result[leftIndex++] = args[argsIndex++];
3503 }
3504 return result;
3505 }
3506
3507 /**
3508 * This function is like `composeArgs` except that the arguments composition
3509 * is tailored for `_.partialRight`.
3510 *
3511 * @private
3512 * @param {Array|Object} args The provided arguments.
3513 * @param {Array} partials The arguments to append to those provided.
3514 * @param {Array} holders The `partials` placeholder indexes.
3515 * @returns {Array} Returns the new array of composed arguments.
3516 */
3517 function composeArgsRight(args, partials, holders) {
3518 var holdersIndex = -1,
3519 holdersLength = holders.length,
3520 argsIndex = -1,
3521 argsLength = nativeMax(args.length - holdersLength, 0),
3522 rightIndex = -1,
3523 rightLength = partials.length,
3524 result = Array(argsLength + rightLength);
3525
3526 while (++argsIndex < argsLength) {
3527 result[argsIndex] = args[argsIndex];
3528 }
3529 var offset = argsIndex;
3530 while (++rightIndex < rightLength) {
3531 result[offset + rightIndex] = partials[rightIndex];
3532 }
3533 while (++holdersIndex < holdersLength) {
3534 result[offset + holders[holdersIndex]] = args[argsIndex++];
3535 }
3536 return result;
3537 }
3538
3539 /**
3540 * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
3541 *
3542 * @private
3543 * @param {Function} setter The function to set keys and values of the accumulator object.
3544 * @param {Function} [initializer] The function to initialize the accumulator object.
3545 * @returns {Function} Returns the new aggregator function.
3546 */
3547 function createAggregator(setter, initializer) {
3548 return function(collection, iteratee, thisArg) {
3549 var result = initializer ? initializer() : {};
3550 iteratee = getCallback(iteratee, thisArg, 3);
3551
3552 if (isArray(collection)) {
3553 var index = -1,
3554 length = collection.length;
3555
3556 while (++index < length) {
3557 var value = collection[index];
3558 setter(result, value, iteratee(value, index, collection), collection);
3559 }
3560 } else {
3561 baseEach(collection, function(value, key, collection) {
3562 setter(result, value, iteratee(value, key, collection), collection);
3563 });
3564 }
3565 return result;
3566 };
3567 }
3568
3569 /**
3570 * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
3571 *
3572 * @private
3573 * @param {Function} assigner The function to assign values.
3574 * @returns {Function} Returns the new assigner function.
3575 */
3576 function createAssigner(assigner) {
3577 return restParam(function(object, sources) {
3578 var index = -1,
3579 length = object == null ? 0 : sources.length,
3580 customizer = length > 2 ? sources[length - 2] : undefined,
3581 guard = length > 2 ? sources[2] : undefined,
3582 thisArg = length > 1 ? sources[length - 1] : undefined;
3583
3584 if (typeof customizer == 'function') {
3585 customizer = bindCallback(customizer, thisArg, 5);
3586 length -= 2;
3587 } else {
3588 customizer = typeof thisArg == 'function' ? thisArg : undefined;
3589 length -= (customizer ? 1 : 0);
3590 }
3591 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
3592 customizer = length < 3 ? undefined : customizer;
3593 length = 1;
3594 }
3595 while (++index < length) {
3596 var source = sources[index];
3597 if (source) {
3598 assigner(object, source, customizer);
3599 }
3600 }
3601 return object;
3602 });
3603 }
3604
3605 /**
3606 * Creates a `baseEach` or `baseEachRight` function.
3607 *
3608 * @private
3609 * @param {Function} eachFunc The function to iterate over a collection.
3610 * @param {boolean} [fromRight] Specify iterating from right to left.
3611 * @returns {Function} Returns the new base function.
3612 */
3613 function createBaseEach(eachFunc, fromRight) {
3614 return function(collection, iteratee) {
3615 var length = collection ? getLength(collection) : 0;
3616 if (!isLength(length)) {
3617 return eachFunc(collection, iteratee);
3618 }
3619 var index = fromRight ? length : -1,
3620 iterable = toObject(collection);
3621
3622 while ((fromRight ? index-- : ++index < length)) {
3623 if (iteratee(iterable[index], index, iterable) === false) {
3624 break;
3625 }
3626 }
3627 return collection;
3628 };
3629 }
3630
3631 /**
3632 * Creates a base function for `_.forIn` or `_.forInRight`.
3633 *
3634 * @private
3635 * @param {boolean} [fromRight] Specify iterating from right to left.
3636 * @returns {Function} Returns the new base function.
3637 */
3638 function createBaseFor(fromRight) {
3639 return function(object, iteratee, keysFunc) {
3640 var iterable = toObject(object),
3641 props = keysFunc(object),
3642 length = props.length,
3643 index = fromRight ? length : -1;
3644
3645 while ((fromRight ? index-- : ++index < length)) {
3646 var key = props[index];
3647 if (iteratee(iterable[key], key, iterable) === false) {
3648 break;
3649 }
3650 }
3651 return object;
3652 };
3653 }
3654
3655 /**
3656 * Creates a function that wraps `func` and invokes it with the `this`
3657 * binding of `thisArg`.
3658 *
3659 * @private
3660 * @param {Function} func The function to bind.
3661 * @param {*} [thisArg] The `this` binding of `func`.
3662 * @returns {Function} Returns the new bound function.
3663 */
3664 function createBindWrapper(func, thisArg) {
3665 var Ctor = createCtorWrapper(func);
3666
3667 function wrapper() {
3668 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
3669 return fn.apply(thisArg, arguments);
3670 }
3671 return wrapper;
3672 }
3673
3674 /**
3675 * Creates a `Set` cache object to optimize linear searches of large arrays.
3676 *
3677 * @private
3678 * @param {Array} [values] The values to cache.
3679 * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
3680 */
3681 function createCache(values) {
3682 return (nativeCreate && Set) ? new SetCache(values) : null;
3683 }
3684
3685 /**
3686 * Creates a function that produces compound words out of the words in a
3687 * given string.
3688 *
3689 * @private
3690 * @param {Function} callback The function to combine each word.
3691 * @returns {Function} Returns the new compounder function.
3692 */
3693 function createCompounder(callback) {
3694 return function(string) {
3695 var index = -1,
3696 array = words(deburr(string)),
3697 length = array.length,
3698 result = '';
3699
3700 while (++index < length) {
3701 result = callback(result, array[index], index);
3702 }
3703 return result;
3704 };
3705 }
3706
3707 /**
3708 * Creates a function that produces an instance of `Ctor` regardless of
3709 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
3710 *
3711 * @private
3712 * @param {Function} Ctor The constructor to wrap.
3713 * @returns {Function} Returns the new wrapped function.
3714 */
3715 function createCtorWrapper(Ctor) {
3716 return function() {
3717 // Use a `switch` statement to work with class constructors.
3718 // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
3719 // for more details.
3720 var args = arguments;
3721 switch (args.length) {
3722 case 0: return new Ctor;
3723 case 1: return new Ctor(args[0]);
3724 case 2: return new Ctor(args[0], args[1]);
3725 case 3: return new Ctor(args[0], args[1], args[2]);
3726 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
3727 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
3728 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
3729 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
3730 }
3731 var thisBinding = baseCreate(Ctor.prototype),
3732 result = Ctor.apply(thisBinding, args);
3733
3734 // Mimic the constructor's `return` behavior.
3735 // See https://es5.github.io/#x13.2.2 for more details.
3736 return isObject(result) ? result : thisBinding;
3737 };
3738 }
3739
3740 /**
3741 * Creates a `_.curry` or `_.curryRight` function.
3742 *
3743 * @private
3744 * @param {boolean} flag The curry bit flag.
3745 * @returns {Function} Returns the new curry function.
3746 */
3747 function createCurry(flag) {
3748 function curryFunc(func, arity, guard) {
3749 if (guard && isIterateeCall(func, arity, guard)) {
3750 arity = undefined;
3751 }
3752 var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity);
3753 result.placeholder = curryFunc.placeholder;
3754 return result;
3755 }
3756 return curryFunc;
3757 }
3758
3759 /**
3760 * Creates a `_.defaults` or `_.defaultsDeep` function.
3761 *
3762 * @private
3763 * @param {Function} assigner The function to assign values.
3764 * @param {Function} customizer The function to customize assigned values.
3765 * @returns {Function} Returns the new defaults function.
3766 */
3767 function createDefaults(assigner, customizer) {
3768 return restParam(function(args) {
3769 var object = args[0];
3770 if (object == null) {
3771 return object;
3772 }
3773 args.push(customizer);
3774 return assigner.apply(undefined, args);
3775 });
3776 }
3777
3778 /**
3779 * Creates a `_.max` or `_.min` function.
3780 *
3781 * @private
3782 * @param {Function} comparator The function used to compare values.
3783 * @param {*} exValue The initial extremum value.
3784 * @returns {Function} Returns the new extremum function.
3785 */
3786 function createExtremum(comparator, exValue) {
3787 return function(collection, iteratee, thisArg) {
3788 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
3789 iteratee = undefined;
3790 }
3791 iteratee = getCallback(iteratee, thisArg, 3);
3792 if (iteratee.length == 1) {
3793 collection = isArray(collection) ? collection : toIterable(collection);
3794 var result = arrayExtremum(collection, iteratee, comparator, exValue);
3795 if (!(collection.length && result === exValue)) {
3796 return result;
3797 }
3798 }
3799 return baseExtremum(collection, iteratee, comparator, exValue);
3800 };
3801 }
3802
3803 /**
3804 * Creates a `_.find` or `_.findLast` function.
3805 *
3806 * @private
3807 * @param {Function} eachFunc The function to iterate over a collection.
3808 * @param {boolean} [fromRight] Specify iterating from right to left.
3809 * @returns {Function} Returns the new find function.
3810 */
3811 function createFind(eachFunc, fromRight) {
3812 return function(collection, predicate, thisArg) {
3813 predicate = getCallback(predicate, thisArg, 3);
3814 if (isArray(collection)) {
3815 var index = baseFindIndex(collection, predicate, fromRight);
3816 return index > -1 ? collection[index] : undefined;
3817 }
3818 return baseFind(collection, predicate, eachFunc);
3819 };
3820 }
3821
3822 /**
3823 * Creates a `_.findIndex` or `_.findLastIndex` function.
3824 *
3825 * @private
3826 * @param {boolean} [fromRight] Specify iterating from right to left.
3827 * @returns {Function} Returns the new find function.
3828 */
3829 function createFindIndex(fromRight) {
3830 return function(array, predicate, thisArg) {
3831 if (!(array && array.length)) {
3832 return -1;
3833 }
3834 predicate = getCallback(predicate, thisArg, 3);
3835 return baseFindIndex(array, predicate, fromRight);
3836 };
3837 }
3838
3839 /**
3840 * Creates a `_.findKey` or `_.findLastKey` function.
3841 *
3842 * @private
3843 * @param {Function} objectFunc The function to iterate over an object.
3844 * @returns {Function} Returns the new find function.
3845 */
3846 function createFindKey(objectFunc) {
3847 return function(object, predicate, thisArg) {
3848 predicate = getCallback(predicate, thisArg, 3);
3849 return baseFind(object, predicate, objectFunc, true);
3850 };
3851 }
3852
3853 /**
3854 * Creates a `_.flow` or `_.flowRight` function.
3855 *
3856 * @private
3857 * @param {boolean} [fromRight] Specify iterating from right to left.
3858 * @returns {Function} Returns the new flow function.
3859 */
3860 function createFlow(fromRight) {
3861 return function() {
3862 var wrapper,
3863 length = arguments.length,
3864 index = fromRight ? length : -1,
3865 leftIndex = 0,
3866 funcs = Array(length);
3867
3868 while ((fromRight ? index-- : ++index < length)) {
3869 var func = funcs[leftIndex++] = arguments[index];
3870 if (typeof func != 'function') {
3871 throw new TypeError(FUNC_ERROR_TEXT);
3872 }
3873 if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
3874 wrapper = new LodashWrapper([], true);
3875 }
3876 }
3877 index = wrapper ? -1 : length;
3878 while (++index < length) {
3879 func = funcs[index];
3880
3881 var funcName = getFuncName(func),
3882 data = funcName == 'wrapper' ? getData(func) : undefined;
3883
3884 if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
3885 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
3886 } else {
3887 wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
3888 }
3889 }
3890 return function() {
3891 var args = arguments,
3892 value = args[0];
3893
3894 if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
3895 return wrapper.plant(value).value();
3896 }
3897 var index = 0,
3898 result = length ? funcs[index].apply(this, args) : value;
3899
3900 while (++index < length) {
3901 result = funcs[index].call(this, result);
3902 }
3903 return result;
3904 };
3905 };
3906 }
3907
3908 /**
3909 * Creates a function for `_.forEach` or `_.forEachRight`.
3910 *
3911 * @private
3912 * @param {Function} arrayFunc The function to iterate over an array.
3913 * @param {Function} eachFunc The function to iterate over a collection.
3914 * @returns {Function} Returns the new each function.
3915 */
3916 function createForEach(arrayFunc, eachFunc) {
3917 return function(collection, iteratee, thisArg) {
3918 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
3919 ? arrayFunc(collection, iteratee)
3920 : eachFunc(collection, bindCallback(iteratee, thisArg, 3));
3921 };
3922 }
3923
3924 /**
3925 * Creates a function for `_.forIn` or `_.forInRight`.
3926 *
3927 * @private
3928 * @param {Function} objectFunc The function to iterate over an object.
3929 * @returns {Function} Returns the new each function.
3930 */
3931 function createForIn(objectFunc) {
3932 return function(object, iteratee, thisArg) {
3933 if (typeof iteratee != 'function' || thisArg !== undefined) {
3934 iteratee = bindCallback(iteratee, thisArg, 3);
3935 }
3936 return objectFunc(object, iteratee, keysIn);
3937 };
3938 }
3939
3940 /**
3941 * Creates a function for `_.forOwn` or `_.forOwnRight`.
3942 *
3943 * @private
3944 * @param {Function} objectFunc The function to iterate over an object.
3945 * @returns {Function} Returns the new each function.
3946 */
3947 function createForOwn(objectFunc) {
3948 return function(object, iteratee, thisArg) {
3949 if (typeof iteratee != 'function' || thisArg !== undefined) {
3950 iteratee = bindCallback(iteratee, thisArg, 3);
3951 }
3952 return objectFunc(object, iteratee);
3953 };
3954 }
3955
3956 /**
3957 * Creates a function for `_.mapKeys` or `_.mapValues`.
3958 *
3959 * @private
3960 * @param {boolean} [isMapKeys] Specify mapping keys instead of values.
3961 * @returns {Function} Returns the new map function.
3962 */
3963 function createObjectMapper(isMapKeys) {
3964 return function(object, iteratee, thisArg) {
3965 var result = {};
3966 iteratee = getCallback(iteratee, thisArg, 3);
3967
3968 baseForOwn(object, function(value, key, object) {
3969 var mapped = iteratee(value, key, object);
3970 key = isMapKeys ? mapped : key;
3971 value = isMapKeys ? value : mapped;
3972 result[key] = value;
3973 });
3974 return result;
3975 };
3976 }
3977
3978 /**
3979 * Creates a function for `_.padLeft` or `_.padRight`.
3980 *
3981 * @private
3982 * @param {boolean} [fromRight] Specify padding from the right.
3983 * @returns {Function} Returns the new pad function.
3984 */
3985 function createPadDir(fromRight) {
3986 return function(string, length, chars) {
3987 string = baseToString(string);
3988 return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
3989 };
3990 }
3991
3992 /**
3993 * Creates a `_.partial` or `_.partialRight` function.
3994 *
3995 * @private
3996 * @param {boolean} flag The partial bit flag.
3997 * @returns {Function} Returns the new partial function.
3998 */
3999 function createPartial(flag) {
4000 var partialFunc = restParam(function(func, partials) {
4001 var holders = replaceHolders(partials, partialFunc.placeholder);
4002 return createWrapper(func, flag, undefined, partials, holders);
4003 });
4004 return partialFunc;
4005 }
4006
4007 /**
4008 * Creates a function for `_.reduce` or `_.reduceRight`.
4009 *
4010 * @private
4011 * @param {Function} arrayFunc The function to iterate over an array.
4012 * @param {Function} eachFunc The function to iterate over a collection.
4013 * @returns {Function} Returns the new each function.
4014 */
4015 function createReduce(arrayFunc, eachFunc) {
4016 return function(collection, iteratee, accumulator, thisArg) {
4017 var initFromArray = arguments.length < 3;
4018 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
4019 ? arrayFunc(collection, iteratee, accumulator, initFromArray)
4020 : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
4021 };
4022 }
4023
4024 /**
4025 * Creates a function that wraps `func` and invokes it with optional `this`
4026 * binding of, partial application, and currying.
4027 *
4028 * @private
4029 * @param {Function|string} func The function or method name to reference.
4030 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
4031 * @param {*} [thisArg] The `this` binding of `func`.
4032 * @param {Array} [partials] The arguments to prepend to those provided to the new function.
4033 * @param {Array} [holders] The `partials` placeholder indexes.
4034 * @param {Array} [partialsRight] The arguments to append to those provided to the new function.
4035 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
4036 * @param {Array} [argPos] The argument positions of the new function.
4037 * @param {number} [ary] The arity cap of `func`.
4038 * @param {number} [arity] The arity of `func`.
4039 * @returns {Function} Returns the new wrapped function.
4040 */
4041 function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
4042 var isAry = bitmask & ARY_FLAG,
4043 isBind = bitmask & BIND_FLAG,
4044 isBindKey = bitmask & BIND_KEY_FLAG,
4045 isCurry = bitmask & CURRY_FLAG,
4046 isCurryBound = bitmask & CURRY_BOUND_FLAG,
4047 isCurryRight = bitmask & CURRY_RIGHT_FLAG,
4048 Ctor = isBindKey ? undefined : createCtorWrapper(func);
4049
4050 function wrapper() {
4051 // Avoid `arguments` object use disqualifying optimizations by
4052 // converting it to an array before providing it to other functions.
4053 var length = arguments.length,
4054 index = length,
4055 args = Array(length);
4056
4057 while (index--) {
4058 args[index] = arguments[index];
4059 }
4060 if (partials) {
4061 args = composeArgs(args, partials, holders);
4062 }
4063 if (partialsRight) {
4064 args = composeArgsRight(args, partialsRight, holdersRight);
4065 }
4066 if (isCurry || isCurryRight) {
4067 var placeholder = wrapper.placeholder,
4068 argsHolders = replaceHolders(args, placeholder);
4069
4070 length -= argsHolders.length;
4071 if (length < arity) {
4072 var newArgPos = argPos ? arrayCopy(argPos) : undefined,
4073 newArity = nativeMax(arity - length, 0),
4074 newsHolders = isCurry ? argsHolders : undefined,
4075 newHoldersRight = isCurry ? undefined : argsHolders,
4076 newPartials = isCurry ? args : undefined,
4077 newPartialsRight = isCurry ? undefined : args;
4078
4079 bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
4080 bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
4081
4082 if (!isCurryBound) {
4083 bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
4084 }
4085 var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
4086 result = createHybridWrapper.apply(undefined, newData);
4087
4088 if (isLaziable(func)) {
4089 setData(result, newData);
4090 }
4091 result.placeholder = placeholder;
4092 return result;
4093 }
4094 }
4095 var thisBinding = isBind ? thisArg : this,
4096 fn = isBindKey ? thisBinding[func] : func;
4097
4098 if (argPos) {
4099 args = reorder(args, argPos);
4100 }
4101 if (isAry && ary < args.length) {
4102 args.length = ary;
4103 }
4104 if (this && this !== root && this instanceof wrapper) {
4105 fn = Ctor || createCtorWrapper(func);
4106 }
4107 return fn.apply(thisBinding, args);
4108 }
4109 return wrapper;
4110 }
4111
4112 /**
4113 * Creates the padding required for `string` based on the given `length`.
4114 * The `chars` string is truncated if the number of characters exceeds `length`.
4115 *
4116 * @private
4117 * @param {string} string The string to create padding for.
4118 * @param {number} [length=0] The padding length.
4119 * @param {string} [chars=' '] The string used as padding.
4120 * @returns {string} Returns the pad for `string`.
4121 */
4122 function createPadding(string, length, chars) {
4123 var strLength = string.length;
4124 length = +length;
4125
4126 if (strLength >= length || !nativeIsFinite(length)) {
4127 return '';
4128 }
4129 var padLength = length - strLength;
4130 chars = chars == null ? ' ' : (chars + '');
4131 return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
4132 }
4133
4134 /**
4135 * Creates a function that wraps `func` and invokes it with the optional `this`
4136 * binding of `thisArg` and the `partials` prepended to those provided to
4137 * the wrapper.
4138 *
4139 * @private
4140 * @param {Function} func The function to partially apply arguments to.
4141 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
4142 * @param {*} thisArg The `this` binding of `func`.
4143 * @param {Array} partials The arguments to prepend to those provided to the new function.
4144 * @returns {Function} Returns the new bound function.
4145 */
4146 function createPartialWrapper(func, bitmask, thisArg, partials) {
4147 var isBind = bitmask & BIND_FLAG,
4148 Ctor = createCtorWrapper(func);
4149
4150 function wrapper() {
4151 // Avoid `arguments` object use disqualifying optimizations by
4152 // converting it to an array before providing it `func`.
4153 var argsIndex = -1,
4154 argsLength = arguments.length,
4155 leftIndex = -1,
4156 leftLength = partials.length,
4157 args = Array(leftLength + argsLength);
4158
4159 while (++leftIndex < leftLength) {
4160 args[leftIndex] = partials[leftIndex];
4161 }
4162 while (argsLength--) {
4163 args[leftIndex++] = arguments[++argsIndex];
4164 }
4165 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
4166 return fn.apply(isBind ? thisArg : this, args);
4167 }
4168 return wrapper;
4169 }
4170
4171 /**
4172 * Creates a `_.ceil`, `_.floor`, or `_.round` function.
4173 *
4174 * @private
4175 * @param {string} methodName The name of the `Math` method to use when rounding.
4176 * @returns {Function} Returns the new round function.
4177 */
4178 function createRound(methodName) {
4179 var func = Math[methodName];
4180 return function(number, precision) {
4181 precision = precision === undefined ? 0 : (+precision || 0);
4182 if (precision) {
4183 precision = pow(10, precision);
4184 return func(number * precision) / precision;
4185 }
4186 return func(number);
4187 };
4188 }
4189
4190 /**
4191 * Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
4192 *
4193 * @private
4194 * @param {boolean} [retHighest] Specify returning the highest qualified index.
4195 * @returns {Function} Returns the new index function.
4196 */
4197 function createSortedIndex(retHighest) {
4198 return function(array, value, iteratee, thisArg) {
4199 var callback = getCallback(iteratee);
4200 return (iteratee == null && callback === baseCallback)
4201 ? binaryIndex(array, value, retHighest)
4202 : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
4203 };
4204 }
4205
4206 /**
4207 * Creates a function that either curries or invokes `func` with optional
4208 * `this` binding and partially applied arguments.
4209 *
4210 * @private
4211 * @param {Function|string} func The function or method name to reference.
4212 * @param {number} bitmask The bitmask of flags.
4213 * The bitmask may be composed of the following flags:
4214 * 1 - `_.bind`
4215 * 2 - `_.bindKey`
4216 * 4 - `_.curry` or `_.curryRight` of a bound function
4217 * 8 - `_.curry`
4218 * 16 - `_.curryRight`
4219 * 32 - `_.partial`
4220 * 64 - `_.partialRight`
4221 * 128 - `_.rearg`
4222 * 256 - `_.ary`
4223 * @param {*} [thisArg] The `this` binding of `func`.
4224 * @param {Array} [partials] The arguments to be partially applied.
4225 * @param {Array} [holders] The `partials` placeholder indexes.
4226 * @param {Array} [argPos] The argument positions of the new function.
4227 * @param {number} [ary] The arity cap of `func`.
4228 * @param {number} [arity] The arity of `func`.
4229 * @returns {Function} Returns the new wrapped function.
4230 */
4231 function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
4232 var isBindKey = bitmask & BIND_KEY_FLAG;
4233 if (!isBindKey && typeof func != 'function') {
4234 throw new TypeError(FUNC_ERROR_TEXT);
4235 }
4236 var length = partials ? partials.length : 0;
4237 if (!length) {
4238 bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
4239 partials = holders = undefined;
4240 }
4241 length -= (holders ? holders.length : 0);
4242 if (bitmask & PARTIAL_RIGHT_FLAG) {
4243 var partialsRight = partials,
4244 holdersRight = holders;
4245
4246 partials = holders = undefined;
4247 }
4248 var data = isBindKey ? undefined : getData(func),
4249 newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
4250
4251 if (data) {
4252 mergeData(newData, data);
4253 bitmask = newData[1];
4254 arity = newData[9];
4255 }
4256 newData[9] = arity == null
4257 ? (isBindKey ? 0 : func.length)
4258 : (nativeMax(arity - length, 0) || 0);
4259
4260 if (bitmask == BIND_FLAG) {
4261 var result = createBindWrapper(newData[0], newData[2]);
4262 } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
4263 result = createPartialWrapper.apply(undefined, newData);
4264 } else {
4265 result = createHybridWrapper.apply(undefined, newData);
4266 }
4267 var setter = data ? baseSetData : setData;
4268 return setter(result, newData);
4269 }
4270
4271 /**
4272 * A specialized version of `baseIsEqualDeep` for arrays with support for
4273 * partial deep comparisons.
4274 *
4275 * @private
4276 * @param {Array} array The array to compare.
4277 * @param {Array} other The other array to compare.
4278 * @param {Function} equalFunc The function to determine equivalents of values.
4279 * @param {Function} [customizer] The function to customize comparing arrays.
4280 * @param {boolean} [isLoose] Specify performing partial comparisons.
4281 * @param {Array} [stackA] Tracks traversed `value` objects.
4282 * @param {Array} [stackB] Tracks traversed `other` objects.
4283 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
4284 */
4285 function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
4286 var index = -1,
4287 arrLength = array.length,
4288 othLength = other.length;
4289
4290 if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
4291 return false;
4292 }
4293 // Ignore non-index properties.
4294 while (++index < arrLength) {
4295 var arrValue = array[index],
4296 othValue = other[index],
4297 result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
4298
4299 if (result !== undefined) {
4300 if (result) {
4301 continue;
4302 }
4303 return false;
4304 }
4305 // Recursively compare arrays (susceptible to call stack limits).
4306 if (isLoose) {
4307 if (!arraySome(other, function(othValue) {
4308 return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
4309 })) {
4310 return false;
4311 }
4312 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
4313 return false;
4314 }
4315 }
4316 return true;
4317 }
4318
4319 /**
4320 * A specialized version of `baseIsEqualDeep` for comparing objects of
4321 * the same `toStringTag`.
4322 *
4323 * **Note:** This function only supports comparing values with tags of
4324 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
4325 *
4326 * @private
4327 * @param {Object} object The object to compare.
4328 * @param {Object} other The other object to compare.
4329 * @param {string} tag The `toStringTag` of the objects to compare.
4330 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
4331 */
4332 function equalByTag(object, other, tag) {
4333 switch (tag) {
4334 case boolTag:
4335 case dateTag:
4336 // Coerce dates and booleans to numbers, dates to milliseconds and booleans
4337 // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
4338 return +object == +other;
4339
4340 case errorTag:
4341 return object.name == other.name && object.message == other.message;
4342
4343 case numberTag:
4344 // Treat `NaN` vs. `NaN` as equal.
4345 return (object != +object)
4346 ? other != +other
4347 : object == +other;
4348
4349 case regexpTag:
4350 case stringTag:
4351 // Coerce regexes to strings and treat strings primitives and string
4352 // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
4353 return object == (other + '');
4354 }
4355 return false;
4356 }
4357
4358 /**
4359 * A specialized version of `baseIsEqualDeep` for objects with support for
4360 * partial deep comparisons.
4361 *
4362 * @private
4363 * @param {Object} object The object to compare.
4364 * @param {Object} other The other object to compare.
4365 * @param {Function} equalFunc The function to determine equivalents of values.
4366 * @param {Function} [customizer] The function to customize comparing values.
4367 * @param {boolean} [isLoose] Specify performing partial comparisons.
4368 * @param {Array} [stackA] Tracks traversed `value` objects.
4369 * @param {Array} [stackB] Tracks traversed `other` objects.
4370 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
4371 */
4372 function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
4373 var objProps = keys(object),
4374 objLength = objProps.length,
4375 othProps = keys(other),
4376 othLength = othProps.length;
4377
4378 if (objLength != othLength && !isLoose) {
4379 return false;
4380 }
4381 var index = objLength;
4382 while (index--) {
4383 var key = objProps[index];
4384 if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
4385 return false;
4386 }
4387 }
4388 var skipCtor = isLoose;
4389 while (++index < objLength) {
4390 key = objProps[index];
4391 var objValue = object[key],
4392 othValue = other[key],
4393 result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
4394
4395 // Recursively compare objects (susceptible to call stack limits).
4396 if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
4397 return false;
4398 }
4399 skipCtor || (skipCtor = key == 'constructor');
4400 }
4401 if (!skipCtor) {
4402 var objCtor = object.constructor,
4403 othCtor = other.constructor;
4404
4405 // Non `Object` object instances with different constructors are not equal.
4406 if (objCtor != othCtor &&
4407 ('constructor' in object && 'constructor' in other) &&
4408 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
4409 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
4410 return false;
4411 }
4412 }
4413 return true;
4414 }
4415
4416 /**
4417 * Gets the appropriate "callback" function. If the `_.callback` method is
4418 * customized this function returns the custom method, otherwise it returns
4419 * the `baseCallback` function. If arguments are provided the chosen function
4420 * is invoked with them and its result is returned.
4421 *
4422 * @private
4423 * @returns {Function} Returns the chosen function or its result.
4424 */
4425 function getCallback(func, thisArg, argCount) {
4426 var result = lodash.callback || callback;
4427 result = result === callback ? baseCallback : result;
4428 return argCount ? result(func, thisArg, argCount) : result;
4429 }
4430
4431 /**
4432 * Gets metadata for `func`.
4433 *
4434 * @private
4435 * @param {Function} func The function to query.
4436 * @returns {*} Returns the metadata for `func`.
4437 */
4438 var getData = !metaMap ? noop : function(func) {
4439 return metaMap.get(func);
4440 };
4441
4442 /**
4443 * Gets the name of `func`.
4444 *
4445 * @private
4446 * @param {Function} func The function to query.
4447 * @returns {string} Returns the function name.
4448 */
4449 function getFuncName(func) {
4450 var result = func.name,
4451 array = realNames[result],
4452 length = array ? array.length : 0;
4453
4454 while (length--) {
4455 var data = array[length],
4456 otherFunc = data.func;
4457 if (otherFunc == null || otherFunc == func) {
4458 return data.name;
4459 }
4460 }
4461 return result;
4462 }
4463
4464 /**
4465 * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
4466 * customized this function returns the custom method, otherwise it returns
4467 * the `baseIndexOf` function. If arguments are provided the chosen function
4468 * is invoked with them and its result is returned.
4469 *
4470 * @private
4471 * @returns {Function|number} Returns the chosen function or its result.
4472 */
4473 function getIndexOf(collection, target, fromIndex) {
4474 var result = lodash.indexOf || indexOf;
4475 result = result === indexOf ? baseIndexOf : result;
4476 return collection ? result(collection, target, fromIndex) : result;
4477 }
4478
4479 /**
4480 * Gets the "length" property value of `object`.
4481 *
4482 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
4483 * that affects Safari on at least iOS 8.1-8.3 ARM64.
4484 *
4485 * @private
4486 * @param {Object} object The object to query.
4487 * @returns {*} Returns the "length" value.
4488 */
4489 var getLength = baseProperty('length');
4490
4491 /**
4492 * Gets the propery names, values, and compare flags of `object`.
4493 *
4494 * @private
4495 * @param {Object} object The object to query.
4496 * @returns {Array} Returns the match data of `object`.
4497 */
4498 function getMatchData(object) {
4499 var result = pairs(object),
4500 length = result.length;
4501
4502 while (length--) {
4503 result[length][2] = isStrictComparable(result[length][1]);
4504 }
4505 return result;
4506 }
4507
4508 /**
4509 * Gets the native function at `key` of `object`.
4510 *
4511 * @private
4512 * @param {Object} object The object to query.
4513 * @param {string} key The key of the method to get.
4514 * @returns {*} Returns the function if it's native, else `undefined`.
4515 */
4516 function getNative(object, key) {
4517 var value = object == null ? undefined : object[key];
4518 return isNative(value) ? value : undefined;
4519 }
4520
4521 /**
4522 * Gets the view, applying any `transforms` to the `start` and `end` positions.
4523 *
4524 * @private
4525 * @param {number} start The start of the view.
4526 * @param {number} end The end of the view.
4527 * @param {Array} transforms The transformations to apply to the view.
4528 * @returns {Object} Returns an object containing the `start` and `end`
4529 * positions of the view.
4530 */
4531 function getView(start, end, transforms) {
4532 var index = -1,
4533 length = transforms.length;
4534
4535 while (++index < length) {
4536 var data = transforms[index],
4537 size = data.size;
4538
4539 switch (data.type) {
4540 case 'drop': start += size; break;
4541 case 'dropRight': end -= size; break;
4542 case 'take': end = nativeMin(end, start + size); break;
4543 case 'takeRight': start = nativeMax(start, end - size); break;
4544 }
4545 }
4546 return { 'start': start, 'end': end };
4547 }
4548
4549 /**
4550 * Initializes an array clone.
4551 *
4552 * @private
4553 * @param {Array} array The array to clone.
4554 * @returns {Array} Returns the initialized clone.
4555 */
4556 function initCloneArray(array) {
4557 var length = array.length,
4558 result = new array.constructor(length);
4559
4560 // Add array properties assigned by `RegExp#exec`.
4561 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
4562 result.index = array.index;
4563 result.input = array.input;
4564 }
4565 return result;
4566 }
4567
4568 /**
4569 * Initializes an object clone.
4570 *
4571 * @private
4572 * @param {Object} object The object to clone.
4573 * @returns {Object} Returns the initialized clone.
4574 */
4575 function initCloneObject(object) {
4576 var Ctor = object.constructor;
4577 if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
4578 Ctor = Object;
4579 }
4580 return new Ctor;
4581 }
4582
4583 /**
4584 * Initializes an object clone based on its `toStringTag`.
4585 *
4586 * **Note:** This function only supports cloning values with tags of
4587 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
4588 *
4589 * @private
4590 * @param {Object} object The object to clone.
4591 * @param {string} tag The `toStringTag` of the object to clone.
4592 * @param {boolean} [isDeep] Specify a deep clone.
4593 * @returns {Object} Returns the initialized clone.
4594 */
4595 function initCloneByTag(object, tag, isDeep) {
4596 var Ctor = object.constructor;
4597 switch (tag) {
4598 case arrayBufferTag:
4599 return bufferClone(object);
4600
4601 case boolTag:
4602 case dateTag:
4603 return new Ctor(+object);
4604
4605 case float32Tag: case float64Tag:
4606 case int8Tag: case int16Tag: case int32Tag:
4607 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
4608 var buffer = object.buffer;
4609 return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
4610
4611 case numberTag:
4612 case stringTag:
4613 return new Ctor(object);
4614
4615 case regexpTag:
4616 var result = new Ctor(object.source, reFlags.exec(object));
4617 result.lastIndex = object.lastIndex;
4618 }
4619 return result;
4620 }
4621
4622 /**
4623 * Invokes the method at `path` on `object`.
4624 *
4625 * @private
4626 * @param {Object} object The object to query.
4627 * @param {Array|string} path The path of the method to invoke.
4628 * @param {Array} args The arguments to invoke the method with.
4629 * @returns {*} Returns the result of the invoked method.
4630 */
4631 function invokePath(object, path, args) {
4632 if (object != null && !isKey(path, object)) {
4633 path = toPath(path);
4634 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
4635 path = last(path);
4636 }
4637 var func = object == null ? object : object[path];
4638 return func == null ? undefined : func.apply(object, args);
4639 }
4640
4641 /**
4642 * Checks if `value` is array-like.
4643 *
4644 * @private
4645 * @param {*} value The value to check.
4646 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
4647 */
4648 function isArrayLike(value) {
4649 return value != null && isLength(getLength(value));
4650 }
4651
4652 /**
4653 * Checks if `value` is a valid array-like index.
4654 *
4655 * @private
4656 * @param {*} value The value to check.
4657 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
4658 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
4659 */
4660 function isIndex(value, length) {
4661 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
4662 length = length == null ? MAX_SAFE_INTEGER : length;
4663 return value > -1 && value % 1 == 0 && value < length;
4664 }
4665
4666 /**
4667 * Checks if the provided arguments are from an iteratee call.
4668 *
4669 * @private
4670 * @param {*} value The potential iteratee value argument.
4671 * @param {*} index The potential iteratee index or key argument.
4672 * @param {*} object The potential iteratee object argument.
4673 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
4674 */
4675 function isIterateeCall(value, index, object) {
4676 if (!isObject(object)) {
4677 return false;
4678 }
4679 var type = typeof index;
4680 if (type == 'number'
4681 ? (isArrayLike(object) && isIndex(index, object.length))
4682 : (type == 'string' && index in object)) {
4683 var other = object[index];
4684 return value === value ? (value === other) : (other !== other);
4685 }
4686 return false;
4687 }
4688
4689 /**
4690 * Checks if `value` is a property name and not a property path.
4691 *
4692 * @private
4693 * @param {*} value The value to check.
4694 * @param {Object} [object] The object to query keys on.
4695 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
4696 */
4697 function isKey(value, object) {
4698 var type = typeof value;
4699 if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
4700 return true;
4701 }
4702 if (isArray(value)) {
4703 return false;
4704 }
4705 var result = !reIsDeepProp.test(value);
4706 return result || (object != null && value in toObject(object));
4707 }
4708
4709 /**
4710 * Checks if `func` has a lazy counterpart.
4711 *
4712 * @private
4713 * @param {Function} func The function to check.
4714 * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
4715 */
4716 function isLaziable(func) {
4717 var funcName = getFuncName(func);
4718 if (!(funcName in LazyWrapper.prototype)) {
4719 return false;
4720 }
4721 var other = lodash[funcName];
4722 if (func === other) {
4723 return true;
4724 }
4725 var data = getData(other);
4726 return !!data && func === data[0];
4727 }
4728
4729 /**
4730 * Checks if `value` is a valid array-like length.
4731 *
4732 * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
4733 *
4734 * @private
4735 * @param {*} value The value to check.
4736 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
4737 */
4738 function isLength(value) {
4739 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
4740 }
4741
4742 /**
4743 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
4744 *
4745 * @private
4746 * @param {*} value The value to check.
4747 * @returns {boolean} Returns `true` if `value` if suitable for strict
4748 * equality comparisons, else `false`.
4749 */
4750 function isStrictComparable(value) {
4751 return value === value && !isObject(value);
4752 }
4753
4754 /**
4755 * Merges the function metadata of `source` into `data`.
4756 *
4757 * Merging metadata reduces the number of wrappers required to invoke a function.
4758 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
4759 * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
4760 * augment function arguments, making the order in which they are executed important,
4761 * preventing the merging of metadata. However, we make an exception for a safe
4762 * common case where curried functions have `_.ary` and or `_.rearg` applied.
4763 *
4764 * @private
4765 * @param {Array} data The destination metadata.
4766 * @param {Array} source The source metadata.
4767 * @returns {Array} Returns `data`.
4768 */
4769 function mergeData(data, source) {
4770 var bitmask = data[1],
4771 srcBitmask = source[1],
4772 newBitmask = bitmask | srcBitmask,
4773 isCommon = newBitmask < ARY_FLAG;
4774
4775 var isCombo =
4776 (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
4777 (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
4778 (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
4779
4780 // Exit early if metadata can't be merged.
4781 if (!(isCommon || isCombo)) {
4782 return data;
4783 }
4784 // Use source `thisArg` if available.
4785 if (srcBitmask & BIND_FLAG) {
4786 data[2] = source[2];
4787 // Set when currying a bound function.
4788 newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
4789 }
4790 // Compose partial arguments.
4791 var value = source[3];
4792 if (value) {
4793 var partials = data[3];
4794 data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
4795 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
4796 }
4797 // Compose partial right arguments.
4798 value = source[5];
4799 if (value) {
4800 partials = data[5];
4801 data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
4802 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
4803 }
4804 // Use source `argPos` if available.
4805 value = source[7];
4806 if (value) {
4807 data[7] = arrayCopy(value);
4808 }
4809 // Use source `ary` if it's smaller.
4810 if (srcBitmask & ARY_FLAG) {
4811 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
4812 }
4813 // Use source `arity` if one is not provided.
4814 if (data[9] == null) {
4815 data[9] = source[9];
4816 }
4817 // Use source `func` and merge bitmasks.
4818 data[0] = source[0];
4819 data[1] = newBitmask;
4820
4821 return data;
4822 }
4823
4824 /**
4825 * Used by `_.defaultsDeep` to customize its `_.merge` use.
4826 *
4827 * @private
4828 * @param {*} objectValue The destination object property value.
4829 * @param {*} sourceValue The source object property value.
4830 * @returns {*} Returns the value to assign to the destination object.
4831 */
4832 function mergeDefaults(objectValue, sourceValue) {
4833 return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
4834 }
4835
4836 /**
4837 * A specialized version of `_.pick` which picks `object` properties specified
4838 * by `props`.
4839 *
4840 * @private
4841 * @param {Object} object The source object.
4842 * @param {string[]} props The property names to pick.
4843 * @returns {Object} Returns the new object.
4844 */
4845 function pickByArray(object, props) {
4846 object = toObject(object);
4847
4848 var index = -1,
4849 length = props.length,
4850 result = {};
4851
4852 while (++index < length) {
4853 var key = props[index];
4854 if (key in object) {
4855 result[key] = object[key];
4856 }
4857 }
4858 return result;
4859 }
4860
4861 /**
4862 * A specialized version of `_.pick` which picks `object` properties `predicate`
4863 * returns truthy for.
4864 *
4865 * @private
4866 * @param {Object} object The source object.
4867 * @param {Function} predicate The function invoked per iteration.
4868 * @returns {Object} Returns the new object.
4869 */
4870 function pickByCallback(object, predicate) {
4871 var result = {};
4872 baseForIn(object, function(value, key, object) {
4873 if (predicate(value, key, object)) {
4874 result[key] = value;
4875 }
4876 });
4877 return result;
4878 }
4879
4880 /**
4881 * Reorder `array` according to the specified indexes where the element at
4882 * the first index is assigned as the first element, the element at
4883 * the second index is assigned as the second element, and so on.
4884 *
4885 * @private
4886 * @param {Array} array The array to reorder.
4887 * @param {Array} indexes The arranged array indexes.
4888 * @returns {Array} Returns `array`.
4889 */
4890 function reorder(array, indexes) {
4891 var arrLength = array.length,
4892 length = nativeMin(indexes.length, arrLength),
4893 oldArray = arrayCopy(array);
4894
4895 while (length--) {
4896 var index = indexes[length];
4897 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
4898 }
4899 return array;
4900 }
4901
4902 /**
4903 * Sets metadata for `func`.
4904 *
4905 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
4906 * period of time, it will trip its breaker and transition to an identity function
4907 * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
4908 * for more details.
4909 *
4910 * @private
4911 * @param {Function} func The function to associate metadata with.
4912 * @param {*} data The metadata.
4913 * @returns {Function} Returns `func`.
4914 */
4915 var setData = (function() {
4916 var count = 0,
4917 lastCalled = 0;
4918
4919 return function(key, value) {
4920 var stamp = now(),
4921 remaining = HOT_SPAN - (stamp - lastCalled);
4922
4923 lastCalled = stamp;
4924 if (remaining > 0) {
4925 if (++count >= HOT_COUNT) {
4926 return key;
4927 }
4928 } else {
4929 count = 0;
4930 }
4931 return baseSetData(key, value);
4932 };
4933 }());
4934
4935 /**
4936 * A fallback implementation of `Object.keys` which creates an array of the
4937 * own enumerable property names of `object`.
4938 *
4939 * @private
4940 * @param {Object} object The object to query.
4941 * @returns {Array} Returns the array of property names.
4942 */
4943 function shimKeys(object) {
4944 var props = keysIn(object),
4945 propsLength = props.length,
4946 length = propsLength && object.length;
4947
4948 var allowIndexes = !!length && isLength(length) &&
4949 (isArray(object) || isArguments(object));
4950
4951 var index = -1,
4952 result = [];
4953
4954 while (++index < propsLength) {
4955 var key = props[index];
4956 if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
4957 result.push(key);
4958 }
4959 }
4960 return result;
4961 }
4962
4963 /**
4964 * Converts `value` to an array-like object if it's not one.
4965 *
4966 * @private
4967 * @param {*} value The value to process.
4968 * @returns {Array|Object} Returns the array-like object.
4969 */
4970 function toIterable(value) {
4971 if (value == null) {
4972 return [];
4973 }
4974 if (!isArrayLike(value)) {
4975 return values(value);
4976 }
4977 return isObject(value) ? value : Object(value);
4978 }
4979
4980 /**
4981 * Converts `value` to an object if it's not one.
4982 *
4983 * @private
4984 * @param {*} value The value to process.
4985 * @returns {Object} Returns the object.
4986 */
4987 function toObject(value) {
4988 return isObject(value) ? value : Object(value);
4989 }
4990
4991 /**
4992 * Converts `value` to property path array if it's not one.
4993 *
4994 * @private
4995 * @param {*} value The value to process.
4996 * @returns {Array} Returns the property path array.
4997 */
4998 function toPath(value) {
4999 if (isArray(value)) {
5000 return value;
5001 }
5002 var result = [];
5003 baseToString(value).replace(rePropName, function(match, number, quote, string) {
5004 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
5005 });
5006 return result;
5007 }
5008
5009 /**
5010 * Creates a clone of `wrapper`.
5011 *
5012 * @private
5013 * @param {Object} wrapper The wrapper to clone.
5014 * @returns {Object} Returns the cloned wrapper.
5015 */
5016 function wrapperClone(wrapper) {
5017 return wrapper instanceof LazyWrapper
5018 ? wrapper.clone()
5019 : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
5020 }
5021
5022 /*------------------------------------------------------------------------*/
5023
5024 /**
5025 * Creates an array of elements split into groups the length of `size`.
5026 * If `collection` can't be split evenly, the final chunk will be the remaining
5027 * elements.
5028 *
5029 * @static
5030 * @memberOf _
5031 * @category Array
5032 * @param {Array} array The array to process.
5033 * @param {number} [size=1] The length of each chunk.
5034 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
5035 * @returns {Array} Returns the new array containing chunks.
5036 * @example
5037 *
5038 * _.chunk(['a', 'b', 'c', 'd'], 2);
5039 * // => [['a', 'b'], ['c', 'd']]
5040 *
5041 * _.chunk(['a', 'b', 'c', 'd'], 3);
5042 * // => [['a', 'b', 'c'], ['d']]
5043 */
5044 function chunk(array, size, guard) {
5045 if (guard ? isIterateeCall(array, size, guard) : size == null) {
5046 size = 1;
5047 } else {
5048 size = nativeMax(nativeFloor(size) || 1, 1);
5049 }
5050 var index = 0,
5051 length = array ? array.length : 0,
5052 resIndex = -1,
5053 result = Array(nativeCeil(length / size));
5054
5055 while (index < length) {
5056 result[++resIndex] = baseSlice(array, index, (index += size));
5057 }
5058 return result;
5059 }
5060
5061 /**
5062 * Creates an array with all falsey values removed. The values `false`, `null`,
5063 * `0`, `""`, `undefined`, and `NaN` are falsey.
5064 *
5065 * @static
5066 * @memberOf _
5067 * @category Array
5068 * @param {Array} array The array to compact.
5069 * @returns {Array} Returns the new array of filtered values.
5070 * @example
5071 *
5072 * _.compact([0, 1, false, 2, '', 3]);
5073 * // => [1, 2, 3]
5074 */
5075 function compact(array) {
5076 var index = -1,
5077 length = array ? array.length : 0,
5078 resIndex = -1,
5079 result = [];
5080
5081 while (++index < length) {
5082 var value = array[index];
5083 if (value) {
5084 result[++resIndex] = value;
5085 }
5086 }
5087 return result;
5088 }
5089
5090 /**
5091 * Creates an array of unique `array` values not included in the other
5092 * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
5093 * for equality comparisons.
5094 *
5095 * @static
5096 * @memberOf _
5097 * @category Array
5098 * @param {Array} array The array to inspect.
5099 * @param {...Array} [values] The arrays of values to exclude.
5100 * @returns {Array} Returns the new array of filtered values.
5101 * @example
5102 *
5103 * _.difference([1, 2, 3], [4, 2]);
5104 * // => [1, 3]
5105 */
5106 var difference = restParam(function(array, values) {
5107 return (isObjectLike(array) && isArrayLike(array))
5108 ? baseDifference(array, baseFlatten(values, false, true))
5109 : [];
5110 });
5111
5112 /**
5113 * Creates a slice of `array` with `n` elements dropped from the beginning.
5114 *
5115 * @static
5116 * @memberOf _
5117 * @category Array
5118 * @param {Array} array The array to query.
5119 * @param {number} [n=1] The number of elements to drop.
5120 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
5121 * @returns {Array} Returns the slice of `array`.
5122 * @example
5123 *
5124 * _.drop([1, 2, 3]);
5125 * // => [2, 3]
5126 *
5127 * _.drop([1, 2, 3], 2);
5128 * // => [3]
5129 *
5130 * _.drop([1, 2, 3], 5);
5131 * // => []
5132 *
5133 * _.drop([1, 2, 3], 0);
5134 * // => [1, 2, 3]
5135 */
5136 function drop(array, n, guard) {
5137 var length = array ? array.length : 0;
5138 if (!length) {
5139 return [];
5140 }
5141 if (guard ? isIterateeCall(array, n, guard) : n == null) {
5142 n = 1;
5143 }
5144 return baseSlice(array, n < 0 ? 0 : n);
5145 }
5146
5147 /**
5148 * Creates a slice of `array` with `n` elements dropped from the end.
5149 *
5150 * @static
5151 * @memberOf _
5152 * @category Array
5153 * @param {Array} array The array to query.
5154 * @param {number} [n=1] The number of elements to drop.
5155 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
5156 * @returns {Array} Returns the slice of `array`.
5157 * @example
5158 *
5159 * _.dropRight([1, 2, 3]);
5160 * // => [1, 2]
5161 *
5162 * _.dropRight([1, 2, 3], 2);
5163 * // => [1]
5164 *
5165 * _.dropRight([1, 2, 3], 5);
5166 * // => []
5167 *
5168 * _.dropRight([1, 2, 3], 0);
5169 * // => [1, 2, 3]
5170 */
5171 function dropRight(array, n, guard) {
5172 var length = array ? array.length : 0;
5173 if (!length) {
5174 return [];
5175 }
5176 if (guard ? isIterateeCall(array, n, guard) : n == null) {
5177 n = 1;
5178 }
5179 n = length - (+n || 0);
5180 return baseSlice(array, 0, n < 0 ? 0 : n);
5181 }
5182
5183 /**
5184 * Creates a slice of `array` excluding elements dropped from the end.
5185 * Elements are dropped until `predicate` returns falsey. The predicate is
5186 * bound to `thisArg` and invoked with three arguments: (value, index, array).
5187 *
5188 * If a property name is provided for `predicate` the created `_.property`
5189 * style callback returns the property value of the given element.
5190 *
5191 * If a value is also provided for `thisArg` the created `_.matchesProperty`
5192 * style callback returns `true` for elements that have a matching property
5193 * value, else `false`.
5194 *
5195 * If an object is provided for `predicate` the created `_.matches` style
5196 * callback returns `true` for elements that match the properties of the given
5197 * object, else `false`.
5198 *
5199 * @static
5200 * @memberOf _
5201 * @category Array
5202 * @param {Array} array The array to query.
5203 * @param {Function|Object|string} [predicate=_.identity] The function invoked
5204 * per iteration.
5205 * @param {*} [thisArg] The `this` binding of `predicate`.
5206 * @returns {Array} Returns the slice of `array`.
5207 * @example
5208 *
5209 * _.dropRightWhile([1, 2, 3], function(n) {
5210 * return n > 1;
5211 * });
5212 * // => [1]
5213 *
5214 * var users = [
5215 * { 'user': 'barney', 'active': true },
5216 * { 'user': 'fred', 'active': false },
5217 * { 'user': 'pebbles', 'active': false }
5218 * ];
5219 *
5220 * // using the `_.matches` callback shorthand
5221 * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
5222 * // => ['barney', 'fred']
5223 *
5224 * // using the `_.matchesProperty` callback shorthand
5225 * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
5226 * // => ['barney']
5227 *
5228 * // using the `_.property` callback shorthand
5229 * _.pluck(_.dropRightWhile(users, 'active'), 'user');
5230 * // => ['barney', 'fred', 'pebbles']
5231 */
5232 function dropRightWhile(array, predicate, thisArg) {
5233 return (array && array.length)
5234 ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
5235 : [];
5236 }
5237
5238 /**
5239 * Creates a slice of `array` excluding elements dropped from the beginning.
5240 * Elements are dropped until `predicate` returns falsey. The predicate is
5241 * bound to `thisArg` and invoked with three arguments: (value, index, array).
5242 *
5243 * If a property name is provided for `predicate` the created `_.property`
5244 * style callback returns the property value of the given element.
5245 *
5246 * If a value is also provided for `thisArg` the created `_.matchesProperty`
5247 * style callback returns `true` for elements that have a matching property
5248 * value, else `false`.
5249 *
5250 * If an object is provided for `predicate` the created `_.matches` style
5251 * callback returns `true` for elements that have the properties of the given
5252 * object, else `false`.
5253 *
5254 * @static
5255 * @memberOf _
5256 * @category Array
5257 * @param {Array} array The array to query.
5258 * @param {Function|Object|string} [predicate=_.identity] The function invoked
5259 * per iteration.
5260 * @param {*} [thisArg] The `this` binding of `predicate`.
5261 * @returns {Array} Returns the slice of `array`.
5262 * @example
5263 *
5264 * _.dropWhile([1, 2, 3], function(n) {
5265 * return n < 3;
5266 * });
5267 * // => [3]
5268 *
5269 * var users = [
5270 * { 'user': 'barney', 'active': false },
5271 * { 'user': 'fred', 'active': false },
5272 * { 'user': 'pebbles', 'active': true }
5273 * ];
5274 *
5275 * // using the `_.matches` callback shorthand
5276 * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
5277 * // => ['fred', 'pebbles']
5278 *
5279 * // using the `_.matchesProperty` callback shorthand
5280 * _.pluck(_.dropWhile(users, 'active', false), 'user');
5281 * // => ['pebbles']
5282 *
5283 * // using the `_.property` callback shorthand
5284 * _.pluck(_.dropWhile(users, 'active'), 'user');
5285 * // => ['barney', 'fred', 'pebbles']
5286 */
5287 function dropWhile(array, predicate, thisArg) {
5288 return (array && array.length)
5289 ? baseWhile(array, getCallback(predicate, thisArg, 3), true)
5290 : [];
5291 }
5292
5293 /**
5294 * Fills elements of `array` with `value` from `start` up to, but not
5295 * including, `end`.
5296 *
5297 * **Note:** This method mutates `array`.
5298 *
5299 * @static
5300 * @memberOf _
5301 * @category Array
5302 * @param {Array} array The array to fill.
5303 * @param {*} value The value to fill `array` with.
5304 * @param {number} [start=0] The start position.
5305 * @param {number} [end=array.length] The end position.
5306 * @returns {Array} Returns `array`.
5307 * @example
5308 *
5309 * var array = [1, 2, 3];
5310 *
5311 * _.fill(array, 'a');
5312 * console.log(array);
5313 * // => ['a', 'a', 'a']
5314 *
5315 * _.fill(Array(3), 2);
5316 * // => [2, 2, 2]
5317 *
5318 * _.fill([4, 6, 8], '*', 1, 2);
5319 * // => [4, '*', 8]
5320 */
5321 function fill(array, value, start, end) {
5322 var length = array ? array.length : 0;
5323 if (!length) {
5324 return [];
5325 }
5326 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
5327 start = 0;
5328 end = length;
5329 }
5330 return baseFill(array, value, start, end);
5331 }
5332
5333 /**
5334 * This method is like `_.find` except that it returns the index of the first
5335 * element `predicate` returns truthy for instead of the element itself.
5336 *
5337 * If a property name is provided for `predicate` the created `_.property`
5338 * style callback returns the property value of the given element.
5339 *
5340 * If a value is also provided for `thisArg` the created `_.matchesProperty`
5341 * style callback returns `true` for elements that have a matching property
5342 * value, else `false`.
5343 *
5344 * If an object is provided for `predicate` the created `_.matches` style
5345 * callback returns `true` for elements that have the properties of the given
5346 * object, else `false`.
5347 *
5348 * @static
5349 * @memberOf _
5350 * @category Array
5351 * @param {Array} array The array to search.
5352 * @param {Function|Object|string} [predicate=_.identity] The function invoked
5353 * per iteration.
5354 * @param {*} [thisArg] The `this` binding of `predicate`.
5355 * @returns {number} Returns the index of the found element, else `-1`.
5356 * @example
5357 *
5358 * var users = [
5359 * { 'user': 'barney', 'active': false },
5360 * { 'user': 'fred', 'active': false },
5361 * { 'user': 'pebbles', 'active': true }
5362 * ];
5363 *
5364 * _.findIndex(users, function(chr) {
5365 * return chr.user == 'barney';
5366 * });
5367 * // => 0
5368 *
5369 * // using the `_.matches` callback shorthand
5370 * _.findIndex(users, { 'user': 'fred', 'active': false });
5371 * // => 1
5372 *
5373 * // using the `_.matchesProperty` callback shorthand
5374 * _.findIndex(users, 'active', false);
5375 * // => 0
5376 *
5377 * // using the `_.property` callback shorthand
5378 * _.findIndex(users, 'active');
5379 * // => 2
5380 */
5381 var findIndex = createFindIndex();
5382
5383 /**
5384 * This method is like `_.findIndex` except that it iterates over elements
5385 * of `collection` from right to left.
5386 *
5387 * If a property name is provided for `predicate` the created `_.property`
5388 * style callback returns the property value of the given element.
5389 *
5390 * If a value is also provided for `thisArg` the created `_.matchesProperty`
5391 * style callback returns `true` for elements that have a matching property
5392 * value, else `false`.
5393 *
5394 * If an object is provided for `predicate` the created `_.matches` style
5395 * callback returns `true` for elements that have the properties of the given
5396 * object, else `false`.
5397 *
5398 * @static
5399 * @memberOf _
5400 * @category Array
5401 * @param {Array} array The array to search.
5402 * @param {Function|Object|string} [predicate=_.identity] The function invoked
5403 * per iteration.
5404 * @param {*} [thisArg] The `this` binding of `predicate`.
5405 * @returns {number} Returns the index of the found element, else `-1`.
5406 * @example
5407 *
5408 * var users = [
5409 * { 'user': 'barney', 'active': true },
5410 * { 'user': 'fred', 'active': false },
5411 * { 'user': 'pebbles', 'active': false }
5412 * ];
5413 *
5414 * _.findLastIndex(users, function(chr) {
5415 * return chr.user == 'pebbles';
5416 * });
5417 * // => 2
5418 *
5419 * // using the `_.matches` callback shorthand
5420 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
5421 * // => 0
5422 *
5423 * // using the `_.matchesProperty` callback shorthand
5424 * _.findLastIndex(users, 'active', false);
5425 * // => 2
5426 *
5427 * // using the `_.property` callback shorthand
5428 * _.findLastIndex(users, 'active');
5429 * // => 0
5430 */
5431 var findLastIndex = createFindIndex(true);
5432
5433 /**
5434 * Gets the first element of `array`.
5435 *
5436 * @static
5437 * @memberOf _
5438 * @alias head
5439 * @category Array
5440 * @param {Array} array The array to query.
5441 * @returns {*} Returns the first element of `array`.
5442 * @example
5443 *
5444 * _.first([1, 2, 3]);
5445 * // => 1
5446 *
5447 * _.first([]);
5448 * // => undefined
5449 */
5450 function first(array) {
5451 return array ? array[0] : undefined;
5452 }
5453
5454 /**
5455 * Flattens a nested array. If `isDeep` is `true` the array is recursively
5456 * flattened, otherwise it is only flattened a single level.
5457 *
5458 * @static
5459 * @memberOf _
5460 * @category Array
5461 * @param {Array} array The array to flatten.
5462 * @param {boolean} [isDeep] Specify a deep flatten.
5463 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
5464 * @returns {Array} Returns the new flattened array.
5465 * @example
5466 *
5467 * _.flatten([1, [2, 3, [4]]]);
5468 * // => [1, 2, 3, [4]]
5469 *
5470 * // using `isDeep`
5471 * _.flatten([1, [2, 3, [4]]], true);
5472 * // => [1, 2, 3, 4]
5473 */
5474 function flatten(array, isDeep, guard) {
5475 var length = array ? array.length : 0;
5476 if (guard && isIterateeCall(array, isDeep, guard)) {
5477 isDeep = false;
5478 }
5479 return length ? baseFlatten(array, isDeep) : [];
5480 }
5481
5482 /**
5483 * Recursively flattens a nested array.
5484 *
5485 * @static
5486 * @memberOf _
5487 * @category Array
5488 * @param {Array} array The array to recursively flatten.
5489 * @returns {Array} Returns the new flattened array.
5490 * @example
5491 *
5492 * _.flattenDeep([1, [2, 3, [4]]]);
5493 * // => [1, 2, 3, 4]
5494 */
5495 function flattenDeep(array) {
5496 var length = array ? array.length : 0;
5497 return length ? baseFlatten(array, true) : [];
5498 }
5499
5500 /**
5501 * Gets the index at which the first occurrence of `value` is found in `array`
5502 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
5503 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
5504 * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
5505 * performs a faster binary search.
5506 *
5507 * @static
5508 * @memberOf _
5509 * @category Array
5510 * @param {Array} array The array to search.
5511 * @param {*} value The value to search for.
5512 * @param {boolean|number} [fromIndex=0] The index to search from or `true`
5513 * to perform a binary search on a sorted array.
5514 * @returns {number} Returns the index of the matched value, else `-1`.
5515 * @example
5516 *
5517 * _.indexOf([1, 2, 1, 2], 2);
5518 * // => 1
5519 *
5520 * // using `fromIndex`
5521 * _.indexOf([1, 2, 1, 2], 2, 2);
5522 * // => 3
5523 *
5524 * // performing a binary search
5525 * _.indexOf([1, 1, 2, 2], 2, true);
5526 * // => 2
5527 */
5528 function indexOf(array, value, fromIndex) {
5529 var length = array ? array.length : 0;
5530 if (!length) {
5531 return -1;
5532 }
5533 if (typeof fromIndex == 'number') {
5534 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
5535 } else if (fromIndex) {
5536 var index = binaryIndex(array, value);
5537 if (index < length &&
5538 (value === value ? (value === array[index]) : (array[index] !== array[index]))) {
5539 return index;
5540 }
5541 return -1;
5542 }
5543 return baseIndexOf(array, value, fromIndex || 0);
5544 }
5545
5546 /**
5547 * Gets all but the last element of `array`.
5548 *
5549 * @static
5550 * @memberOf _
5551 * @category Array
5552 * @param {Array} array The array to query.
5553 * @returns {Array} Returns the slice of `array`.
5554 * @example
5555 *
5556 * _.initial([1, 2, 3]);
5557 * // => [1, 2]
5558 */
5559 function initial(array) {
5560 return dropRight(array, 1);
5561 }
5562
5563 /**
5564 * Creates an array of unique values that are included in all of the provided
5565 * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
5566 * for equality comparisons.
5567 *
5568 * @static
5569 * @memberOf _
5570 * @category Array
5571 * @param {...Array} [arrays] The arrays to inspect.
5572 * @returns {Array} Returns the new array of shared values.
5573 * @example
5574 * _.intersection([1, 2], [4, 2], [2, 1]);
5575 * // => [2]
5576 */
5577 var intersection = restParam(function(arrays) {
5578 var othLength = arrays.length,
5579 othIndex = othLength,
5580 caches = Array(length),
5581 indexOf = getIndexOf(),
5582 isCommon = indexOf == baseIndexOf,
5583 result = [];
5584
5585 while (othIndex--) {
5586 var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
5587 caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
5588 }
5589 var array = arrays[0],
5590 index = -1,
5591 length = array ? array.length : 0,
5592 seen = caches[0];
5593
5594 outer:
5595 while (++index < length) {
5596 value = array[index];
5597 if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
5598 var othIndex = othLength;
5599 while (--othIndex) {
5600 var cache = caches[othIndex];
5601 if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
5602 continue outer;
5603 }
5604 }
5605 if (seen) {
5606 seen.push(value);
5607 }
5608 result.push(value);
5609 }
5610 }
5611 return result;
5612 });
5613
5614 /**
5615 * Gets the last element of `array`.
5616 *
5617 * @static
5618 * @memberOf _
5619 * @category Array
5620 * @param {Array} array The array to query.
5621 * @returns {*} Returns the last element of `array`.
5622 * @example
5623 *
5624 * _.last([1, 2, 3]);
5625 * // => 3
5626 */
5627 function last(array) {
5628 var length = array ? array.length : 0;
5629 return length ? array[length - 1] : undefined;
5630 }
5631
5632 /**
5633 * This method is like `_.indexOf` except that it iterates over elements of
5634 * `array` from right to left.
5635 *
5636 * @static
5637 * @memberOf _
5638 * @category Array
5639 * @param {Array} array The array to search.
5640 * @param {*} value The value to search for.
5641 * @param {boolean|number} [fromIndex=array.length-1] The index to search from
5642 * or `true` to perform a binary search on a sorted array.
5643 * @returns {number} Returns the index of the matched value, else `-1`.
5644 * @example
5645 *
5646 * _.lastIndexOf([1, 2, 1, 2], 2);
5647 * // => 3
5648 *
5649 * // using `fromIndex`
5650 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
5651 * // => 1
5652 *
5653 * // performing a binary search
5654 * _.lastIndexOf([1, 1, 2, 2], 2, true);
5655 * // => 3
5656 */
5657 function lastIndexOf(array, value, fromIndex) {
5658 var length = array ? array.length : 0;
5659 if (!length) {
5660 return -1;
5661 }
5662 var index = length;
5663 if (typeof fromIndex == 'number') {
5664 index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
5665 } else if (fromIndex) {
5666 index = binaryIndex(array, value, true) - 1;
5667 var other = array[index];
5668 if (value === value ? (value === other) : (other !== other)) {
5669 return index;
5670 }
5671 return -1;
5672 }
5673 if (value !== value) {
5674 return indexOfNaN(array, index, true);
5675 }
5676 while (index--) {
5677 if (array[index] === value) {
5678 return index;
5679 }
5680 }
5681 return -1;
5682 }
5683
5684 /**
5685 * Removes all provided values from `array` using
5686 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
5687 * for equality comparisons.
5688 *
5689 * **Note:** Unlike `_.without`, this method mutates `array`.
5690 *
5691 * @static
5692 * @memberOf _
5693 * @category Array
5694 * @param {Array} array The array to modify.
5695 * @param {...*} [values] The values to remove.
5696 * @returns {Array} Returns `array`.
5697 * @example
5698 *
5699 * var array = [1, 2, 3, 1, 2, 3];
5700 *
5701 * _.pull(array, 2, 3);
5702 * console.log(array);
5703 * // => [1, 1]
5704 */
5705 function pull() {
5706 var args = arguments,
5707 array = args[0];
5708
5709 if (!(array && array.length)) {
5710 return array;
5711 }
5712 var index = 0,
5713 indexOf = getIndexOf(),
5714 length = args.length;
5715
5716 while (++index < length) {
5717 var fromIndex = 0,
5718 value = args[index];
5719
5720 while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
5721 splice.call(array, fromIndex, 1);
5722 }
5723 }
5724 return array;
5725 }
5726
5727 /**
5728 * Removes elements from `array` corresponding to the given indexes and returns
5729 * an array of the removed elements. Indexes may be specified as an array of
5730 * indexes or as individual arguments.
5731 *
5732 * **Note:** Unlike `_.at`, this method mutates `array`.
5733 *
5734 * @static
5735 * @memberOf _
5736 * @category Array
5737 * @param {Array} array The array to modify.
5738 * @param {...(number|number[])} [indexes] The indexes of elements to remove,
5739 * specified as individual indexes or arrays of indexes.
5740 * @returns {Array} Returns the new array of removed elements.
5741 * @example
5742 *
5743 * var array = [5, 10, 15, 20];
5744 * var evens = _.pullAt(array, 1, 3);
5745 *
5746 * console.log(array);
5747 * // => [5, 15]
5748 *
5749 * console.log(evens);
5750 * // => [10, 20]
5751 */
5752 var pullAt = restParam(function(array, indexes) {
5753 indexes = baseFlatten(indexes);
5754
5755 var result = baseAt(array, indexes);
5756 basePullAt(array, indexes.sort(baseCompareAscending));
5757 return result;
5758 });
5759
5760 /**
5761 * Removes all elements from `array` that `predicate` returns truthy for
5762 * and returns an array of the removed elements. The predicate is bound to
5763 * `thisArg` and invoked with three arguments: (value, index, array).
5764 *
5765 * If a property name is provided for `predicate` the created `_.property`
5766 * style callback returns the property value of the given element.
5767 *
5768 * If a value is also provided for `thisArg` the created `_.matchesProperty`
5769 * style callback returns `true` for elements that have a matching property
5770 * value, else `false`.
5771 *
5772 * If an object is provided for `predicate` the created `_.matches` style
5773 * callback returns `true` for elements that have the properties of the given
5774 * object, else `false`.
5775 *
5776 * **Note:** Unlike `_.filter`, this method mutates `array`.
5777 *
5778 * @static
5779 * @memberOf _
5780 * @category Array
5781 * @param {Array} array The array to modify.
5782 * @param {Function|Object|string} [predicate=_.identity] The function invoked
5783 * per iteration.
5784 * @param {*} [thisArg] The `this` binding of `predicate`.
5785 * @returns {Array} Returns the new array of removed elements.
5786 * @example
5787 *
5788 * var array = [1, 2, 3, 4];
5789 * var evens = _.remove(array, function(n) {
5790 * return n % 2 == 0;
5791 * });
5792 *
5793 * console.log(array);
5794 * // => [1, 3]
5795 *
5796 * console.log(evens);
5797 * // => [2, 4]
5798 */
5799 function remove(array, predicate, thisArg) {
5800 var result = [];
5801 if (!(array && array.length)) {
5802 return result;
5803 }
5804 var index = -1,
5805 indexes = [],
5806 length = array.length;
5807
5808 predicate = getCallback(predicate, thisArg, 3);
5809 while (++index < length) {
5810 var value = array[index];
5811 if (predicate(value, index, array)) {
5812 result.push(value);
5813 indexes.push(index);
5814 }
5815 }
5816 basePullAt(array, indexes);
5817 return result;
5818 }
5819
5820 /**
5821 * Gets all but the first element of `array`.
5822 *
5823 * @static
5824 * @memberOf _
5825 * @alias tail
5826 * @category Array
5827 * @param {Array} array The array to query.
5828 * @returns {Array} Returns the slice of `array`.
5829 * @example
5830 *
5831 * _.rest([1, 2, 3]);
5832 * // => [2, 3]
5833 */
5834 function rest(array) {
5835 return drop(array, 1);
5836 }
5837
5838 /**
5839 * Creates a slice of `array` from `start` up to, but not including, `end`.
5840 *
5841 * **Note:** This method is used instead of `Array#slice` to support node
5842 * lists in IE < 9 and to ensure dense arrays are returned.
5843 *
5844 * @static
5845 * @memberOf _
5846 * @category Array
5847 * @param {Array} array The array to slice.
5848 * @param {number} [start=0] The start position.
5849 * @param {number} [end=array.length] The end position.
5850 * @returns {Array} Returns the slice of `array`.
5851 */
5852 function slice(array, start, end) {
5853 var length = array ? array.length : 0;
5854 if (!length) {
5855 return [];
5856 }
5857 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
5858 start = 0;
5859 end = length;
5860 }
5861 return baseSlice(array, start, end);
5862 }
5863
5864 /**
5865 * Uses a binary search to determine the lowest index at which `value` should
5866 * be inserted into `array` in order to maintain its sort order. If an iteratee
5867 * function is provided it is invoked for `value` and each element of `array`
5868 * to compute their sort ranking. The iteratee is bound to `thisArg` and
5869 * invoked with one argument; (value).
5870 *
5871 * If a property name is provided for `iteratee` the created `_.property`
5872 * style callback returns the property value of the given element.
5873 *
5874 * If a value is also provided for `thisArg` the created `_.matchesProperty`
5875 * style callback returns `true` for elements that have a matching property
5876 * value, else `false`.
5877 *
5878 * If an object is provided for `iteratee` the created `_.matches` style
5879 * callback returns `true` for elements that have the properties of the given
5880 * object, else `false`.
5881 *
5882 * @static
5883 * @memberOf _
5884 * @category Array
5885 * @param {Array} array The sorted array to inspect.
5886 * @param {*} value The value to evaluate.
5887 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
5888 * per iteration.
5889 * @param {*} [thisArg] The `this` binding of `iteratee`.
5890 * @returns {number} Returns the index at which `value` should be inserted
5891 * into `array`.
5892 * @example
5893 *
5894 * _.sortedIndex([30, 50], 40);
5895 * // => 1
5896 *
5897 * _.sortedIndex([4, 4, 5, 5], 5);
5898 * // => 2
5899 *
5900 * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
5901 *
5902 * // using an iteratee function
5903 * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
5904 * return this.data[word];
5905 * }, dict);
5906 * // => 1
5907 *
5908 * // using the `_.property` callback shorthand
5909 * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
5910 * // => 1
5911 */
5912 var sortedIndex = createSortedIndex();
5913
5914 /**
5915 * This method is like `_.sortedIndex` except that it returns the highest
5916 * index at which `value` should be inserted into `array` in order to
5917 * maintain its sort order.
5918 *
5919 * @static
5920 * @memberOf _
5921 * @category Array
5922 * @param {Array} array The sorted array to inspect.
5923 * @param {*} value The value to evaluate.
5924 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
5925 * per iteration.
5926 * @param {*} [thisArg] The `this` binding of `iteratee`.
5927 * @returns {number} Returns the index at which `value` should be inserted
5928 * into `array`.
5929 * @example
5930 *
5931 * _.sortedLastIndex([4, 4, 5, 5], 5);
5932 * // => 4
5933 */
5934 var sortedLastIndex = createSortedIndex(true);
5935
5936 /**
5937 * Creates a slice of `array` with `n` elements taken from the beginning.
5938 *
5939 * @static
5940 * @memberOf _
5941 * @category Array
5942 * @param {Array} array The array to query.
5943 * @param {number} [n=1] The number of elements to take.
5944 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
5945 * @returns {Array} Returns the slice of `array`.
5946 * @example
5947 *
5948 * _.take([1, 2, 3]);
5949 * // => [1]
5950 *
5951 * _.take([1, 2, 3], 2);
5952 * // => [1, 2]
5953 *
5954 * _.take([1, 2, 3], 5);
5955 * // => [1, 2, 3]
5956 *
5957 * _.take([1, 2, 3], 0);
5958 * // => []
5959 */
5960 function take(array, n, guard) {
5961 var length = array ? array.length : 0;
5962 if (!length) {
5963 return [];
5964 }
5965 if (guard ? isIterateeCall(array, n, guard) : n == null) {
5966 n = 1;
5967 }
5968 return baseSlice(array, 0, n < 0 ? 0 : n);
5969 }
5970
5971 /**
5972 * Creates a slice of `array` with `n` elements taken from the end.
5973 *
5974 * @static
5975 * @memberOf _
5976 * @category Array
5977 * @param {Array} array The array to query.
5978 * @param {number} [n=1] The number of elements to take.
5979 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
5980 * @returns {Array} Returns the slice of `array`.
5981 * @example
5982 *
5983 * _.takeRight([1, 2, 3]);
5984 * // => [3]
5985 *
5986 * _.takeRight([1, 2, 3], 2);
5987 * // => [2, 3]
5988 *
5989 * _.takeRight([1, 2, 3], 5);
5990 * // => [1, 2, 3]
5991 *
5992 * _.takeRight([1, 2, 3], 0);
5993 * // => []
5994 */
5995 function takeRight(array, n, guard) {
5996 var length = array ? array.length : 0;
5997 if (!length) {
5998 return [];
5999 }
6000 if (guard ? isIterateeCall(array, n, guard) : n == null) {
6001 n = 1;
6002 }
6003 n = length - (+n || 0);
6004 return baseSlice(array, n < 0 ? 0 : n);
6005 }
6006
6007 /**
6008 * Creates a slice of `array` with elements taken from the end. Elements are
6009 * taken until `predicate` returns falsey. The predicate is bound to `thisArg`
6010 * and invoked with three arguments: (value, index, array).
6011 *
6012 * If a property name is provided for `predicate` the created `_.property`
6013 * style callback returns the property value of the given element.
6014 *
6015 * If a value is also provided for `thisArg` the created `_.matchesProperty`
6016 * style callback returns `true` for elements that have a matching property
6017 * value, else `false`.
6018 *
6019 * If an object is provided for `predicate` the created `_.matches` style
6020 * callback returns `true` for elements that have the properties of the given
6021 * object, else `false`.
6022 *
6023 * @static
6024 * @memberOf _
6025 * @category Array
6026 * @param {Array} array The array to query.
6027 * @param {Function|Object|string} [predicate=_.identity] The function invoked
6028 * per iteration.
6029 * @param {*} [thisArg] The `this` binding of `predicate`.
6030 * @returns {Array} Returns the slice of `array`.
6031 * @example
6032 *
6033 * _.takeRightWhile([1, 2, 3], function(n) {
6034 * return n > 1;
6035 * });
6036 * // => [2, 3]
6037 *
6038 * var users = [
6039 * { 'user': 'barney', 'active': true },
6040 * { 'user': 'fred', 'active': false },
6041 * { 'user': 'pebbles', 'active': false }
6042 * ];
6043 *
6044 * // using the `_.matches` callback shorthand
6045 * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
6046 * // => ['pebbles']
6047 *
6048 * // using the `_.matchesProperty` callback shorthand
6049 * _.pluck(_.takeRightWhile(users, 'active', false), 'user');
6050 * // => ['fred', 'pebbles']
6051 *
6052 * // using the `_.property` callback shorthand
6053 * _.pluck(_.takeRightWhile(users, 'active'), 'user');
6054 * // => []
6055 */
6056 function takeRightWhile(array, predicate, thisArg) {
6057 return (array && array.length)
6058 ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
6059 : [];
6060 }
6061
6062 /**
6063 * Creates a slice of `array` with elements taken from the beginning. Elements
6064 * are taken until `predicate` returns falsey. The predicate is bound to
6065 * `thisArg` and invoked with three arguments: (value, index, array).
6066 *
6067 * If a property name is provided for `predicate` the created `_.property`
6068 * style callback returns the property value of the given element.
6069 *
6070 * If a value is also provided for `thisArg` the created `_.matchesProperty`
6071 * style callback returns `true` for elements that have a matching property
6072 * value, else `false`.
6073 *
6074 * If an object is provided for `predicate` the created `_.matches` style
6075 * callback returns `true` for elements that have the properties of the given
6076 * object, else `false`.
6077 *
6078 * @static
6079 * @memberOf _
6080 * @category Array
6081 * @param {Array} array The array to query.
6082 * @param {Function|Object|string} [predicate=_.identity] The function invoked
6083 * per iteration.
6084 * @param {*} [thisArg] The `this` binding of `predicate`.
6085 * @returns {Array} Returns the slice of `array`.
6086 * @example
6087 *
6088 * _.takeWhile([1, 2, 3], function(n) {
6089 * return n < 3;
6090 * });
6091 * // => [1, 2]
6092 *
6093 * var users = [
6094 * { 'user': 'barney', 'active': false },
6095 * { 'user': 'fred', 'active': false},
6096 * { 'user': 'pebbles', 'active': true }
6097 * ];
6098 *
6099 * // using the `_.matches` callback shorthand
6100 * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
6101 * // => ['barney']
6102 *
6103 * // using the `_.matchesProperty` callback shorthand
6104 * _.pluck(_.takeWhile(users, 'active', false), 'user');
6105 * // => ['barney', 'fred']
6106 *
6107 * // using the `_.property` callback shorthand
6108 * _.pluck(_.takeWhile(users, 'active'), 'user');
6109 * // => []
6110 */
6111 function takeWhile(array, predicate, thisArg) {
6112 return (array && array.length)
6113 ? baseWhile(array, getCallback(predicate, thisArg, 3))
6114 : [];
6115 }
6116
6117 /**
6118 * Creates an array of unique values, in order, from all of the provided arrays
6119 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
6120 * for equality comparisons.
6121 *
6122 * @static
6123 * @memberOf _
6124 * @category Array
6125 * @param {...Array} [arrays] The arrays to inspect.
6126 * @returns {Array} Returns the new array of combined values.
6127 * @example
6128 *
6129 * _.union([1, 2], [4, 2], [2, 1]);
6130 * // => [1, 2, 4]
6131 */
6132 var union = restParam(function(arrays) {
6133 return baseUniq(baseFlatten(arrays, false, true));
6134 });
6135
6136 /**
6137 * Creates a duplicate-free version of an array, using
6138 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
6139 * for equality comparisons, in which only the first occurence of each element
6140 * is kept. Providing `true` for `isSorted` performs a faster search algorithm
6141 * for sorted arrays. If an iteratee function is provided it is invoked for
6142 * each element in the array to generate the criterion by which uniqueness
6143 * is computed. The `iteratee` is bound to `thisArg` and invoked with three
6144 * arguments: (value, index, array).
6145 *
6146 * If a property name is provided for `iteratee` the created `_.property`
6147 * style callback returns the property value of the given element.
6148 *
6149 * If a value is also provided for `thisArg` the created `_.matchesProperty`
6150 * style callback returns `true` for elements that have a matching property
6151 * value, else `false`.
6152 *
6153 * If an object is provided for `iteratee` the created `_.matches` style
6154 * callback returns `true` for elements that have the properties of the given
6155 * object, else `false`.
6156 *
6157 * @static
6158 * @memberOf _
6159 * @alias unique
6160 * @category Array
6161 * @param {Array} array The array to inspect.
6162 * @param {boolean} [isSorted] Specify the array is sorted.
6163 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
6164 * @param {*} [thisArg] The `this` binding of `iteratee`.
6165 * @returns {Array} Returns the new duplicate-value-free array.
6166 * @example
6167 *
6168 * _.uniq([2, 1, 2]);
6169 * // => [2, 1]
6170 *
6171 * // using `isSorted`
6172 * _.uniq([1, 1, 2], true);
6173 * // => [1, 2]
6174 *
6175 * // using an iteratee function
6176 * _.uniq([1, 2.5, 1.5, 2], function(n) {
6177 * return this.floor(n);
6178 * }, Math);
6179 * // => [1, 2.5]
6180 *
6181 * // using the `_.property` callback shorthand
6182 * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
6183 * // => [{ 'x': 1 }, { 'x': 2 }]
6184 */
6185 function uniq(array, isSorted, iteratee, thisArg) {
6186 var length = array ? array.length : 0;
6187 if (!length) {
6188 return [];
6189 }
6190 if (isSorted != null && typeof isSorted != 'boolean') {
6191 thisArg = iteratee;
6192 iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
6193 isSorted = false;
6194 }
6195 var callback = getCallback();
6196 if (!(iteratee == null && callback === baseCallback)) {
6197 iteratee = callback(iteratee, thisArg, 3);
6198 }
6199 return (isSorted && getIndexOf() == baseIndexOf)
6200 ? sortedUniq(array, iteratee)
6201 : baseUniq(array, iteratee);
6202 }
6203
6204 /**
6205 * This method is like `_.zip` except that it accepts an array of grouped
6206 * elements and creates an array regrouping the elements to their pre-zip
6207 * configuration.
6208 *
6209 * @static
6210 * @memberOf _
6211 * @category Array
6212 * @param {Array} array The array of grouped elements to process.
6213 * @returns {Array} Returns the new array of regrouped elements.
6214 * @example
6215 *
6216 * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
6217 * // => [['fred', 30, true], ['barney', 40, false]]
6218 *
6219 * _.unzip(zipped);
6220 * // => [['fred', 'barney'], [30, 40], [true, false]]
6221 */
6222 function unzip(array) {
6223 if (!(array && array.length)) {
6224 return [];
6225 }
6226 var index = -1,
6227 length = 0;
6228
6229 array = arrayFilter(array, function(group) {
6230 if (isArrayLike(group)) {
6231 length = nativeMax(group.length, length);
6232 return true;
6233 }
6234 });
6235 var result = Array(length);
6236 while (++index < length) {
6237 result[index] = arrayMap(array, baseProperty(index));
6238 }
6239 return result;
6240 }
6241
6242 /**
6243 * This method is like `_.unzip` except that it accepts an iteratee to specify
6244 * how regrouped values should be combined. The `iteratee` is bound to `thisArg`
6245 * and invoked with four arguments: (accumulator, value, index, group).
6246 *
6247 * @static
6248 * @memberOf _
6249 * @category Array
6250 * @param {Array} array The array of grouped elements to process.
6251 * @param {Function} [iteratee] The function to combine regrouped values.
6252 * @param {*} [thisArg] The `this` binding of `iteratee`.
6253 * @returns {Array} Returns the new array of regrouped elements.
6254 * @example
6255 *
6256 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
6257 * // => [[1, 10, 100], [2, 20, 200]]
6258 *
6259 * _.unzipWith(zipped, _.add);
6260 * // => [3, 30, 300]
6261 */
6262 function unzipWith(array, iteratee, thisArg) {
6263 var length = array ? array.length : 0;
6264 if (!length) {
6265 return [];
6266 }
6267 var result = unzip(array);
6268 if (iteratee == null) {
6269 return result;
6270 }
6271 iteratee = bindCallback(iteratee, thisArg, 4);
6272 return arrayMap(result, function(group) {
6273 return arrayReduce(group, iteratee, undefined, true);
6274 });
6275 }
6276
6277 /**
6278 * Creates an array excluding all provided values using
6279 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
6280 * for equality comparisons.
6281 *
6282 * @static
6283 * @memberOf _
6284 * @category Array
6285 * @param {Array} array The array to filter.
6286 * @param {...*} [values] The values to exclude.
6287 * @returns {Array} Returns the new array of filtered values.
6288 * @example
6289 *
6290 * _.without([1, 2, 1, 3], 1, 2);
6291 * // => [3]
6292 */
6293 var without = restParam(function(array, values) {
6294 return isArrayLike(array)
6295 ? baseDifference(array, values)
6296 : [];
6297 });
6298
6299 /**
6300 * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
6301 * of the provided arrays.
6302 *
6303 * @static
6304 * @memberOf _
6305 * @category Array
6306 * @param {...Array} [arrays] The arrays to inspect.
6307 * @returns {Array} Returns the new array of values.
6308 * @example
6309 *
6310 * _.xor([1, 2], [4, 2]);
6311 * // => [1, 4]
6312 */
6313 function xor() {
6314 var index = -1,
6315 length = arguments.length;
6316
6317 while (++index < length) {
6318 var array = arguments[index];
6319 if (isArrayLike(array)) {
6320 var result = result
6321 ? arrayPush(baseDifference(result, array), baseDifference(array, result))
6322 : array;
6323 }
6324 }
6325 return result ? baseUniq(result) : [];
6326 }
6327
6328 /**
6329 * Creates an array of grouped elements, the first of which contains the first
6330 * elements of the given arrays, the second of which contains the second elements
6331 * of the given arrays, and so on.
6332 *
6333 * @static
6334 * @memberOf _
6335 * @category Array
6336 * @param {...Array} [arrays] The arrays to process.
6337 * @returns {Array} Returns the new array of grouped elements.
6338 * @example
6339 *
6340 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
6341 * // => [['fred', 30, true], ['barney', 40, false]]
6342 */
6343 var zip = restParam(unzip);
6344
6345 /**
6346 * The inverse of `_.pairs`; this method returns an object composed from arrays
6347 * of property names and values. Provide either a single two dimensional array,
6348 * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
6349 * and one of corresponding values.
6350 *
6351 * @static
6352 * @memberOf _
6353 * @alias object
6354 * @category Array
6355 * @param {Array} props The property names.
6356 * @param {Array} [values=[]] The property values.
6357 * @returns {Object} Returns the new object.
6358 * @example
6359 *
6360 * _.zipObject([['fred', 30], ['barney', 40]]);
6361 * // => { 'fred': 30, 'barney': 40 }
6362 *
6363 * _.zipObject(['fred', 'barney'], [30, 40]);
6364 * // => { 'fred': 30, 'barney': 40 }
6365 */
6366 function zipObject(props, values) {
6367 var index = -1,
6368 length = props ? props.length : 0,
6369 result = {};
6370
6371 if (length && !values && !isArray(props[0])) {
6372 values = [];
6373 }
6374 while (++index < length) {
6375 var key = props[index];
6376 if (values) {
6377 result[key] = values[index];
6378 } else if (key) {
6379 result[key[0]] = key[1];
6380 }
6381 }
6382 return result;
6383 }
6384
6385 /**
6386 * This method is like `_.zip` except that it accepts an iteratee to specify
6387 * how grouped values should be combined. The `iteratee` is bound to `thisArg`
6388 * and invoked with four arguments: (accumulator, value, index, group).
6389 *
6390 * @static
6391 * @memberOf _
6392 * @category Array
6393 * @param {...Array} [arrays] The arrays to process.
6394 * @param {Function} [iteratee] The function to combine grouped values.
6395 * @param {*} [thisArg] The `this` binding of `iteratee`.
6396 * @returns {Array} Returns the new array of grouped elements.
6397 * @example
6398 *
6399 * _.zipWith([1, 2], [10, 20], [100, 200], _.add);
6400 * // => [111, 222]
6401 */
6402 var zipWith = restParam(function(arrays) {
6403 var length = arrays.length,
6404 iteratee = length > 2 ? arrays[length - 2] : undefined,
6405 thisArg = length > 1 ? arrays[length - 1] : undefined;
6406
6407 if (length > 2 && typeof iteratee == 'function') {
6408 length -= 2;
6409 } else {
6410 iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
6411 thisArg = undefined;
6412 }
6413 arrays.length = length;
6414 return unzipWith(arrays, iteratee, thisArg);
6415 });
6416
6417 /*------------------------------------------------------------------------*/
6418
6419 /**
6420 * Creates a `lodash` object that wraps `value` with explicit method
6421 * chaining enabled.
6422 *
6423 * @static
6424 * @memberOf _
6425 * @category Chain
6426 * @param {*} value The value to wrap.
6427 * @returns {Object} Returns the new `lodash` wrapper instance.
6428 * @example
6429 *
6430 * var users = [
6431 * { 'user': 'barney', 'age': 36 },
6432 * { 'user': 'fred', 'age': 40 },
6433 * { 'user': 'pebbles', 'age': 1 }
6434 * ];
6435 *
6436 * var youngest = _.chain(users)
6437 * .sortBy('age')
6438 * .map(function(chr) {
6439 * return chr.user + ' is ' + chr.age;
6440 * })
6441 * .first()
6442 * .value();
6443 * // => 'pebbles is 1'
6444 */
6445 function chain(value) {
6446 var result = lodash(value);
6447 result.__chain__ = true;
6448 return result;
6449 }
6450
6451 /**
6452 * This method invokes `interceptor` and returns `value`. The interceptor is
6453 * bound to `thisArg` and invoked with one argument; (value). The purpose of
6454 * this method is to "tap into" a method chain in order to perform operations
6455 * on intermediate results within the chain.
6456 *
6457 * @static
6458 * @memberOf _
6459 * @category Chain
6460 * @param {*} value The value to provide to `interceptor`.
6461 * @param {Function} interceptor The function to invoke.
6462 * @param {*} [thisArg] The `this` binding of `interceptor`.
6463 * @returns {*} Returns `value`.
6464 * @example
6465 *
6466 * _([1, 2, 3])
6467 * .tap(function(array) {
6468 * array.pop();
6469 * })
6470 * .reverse()
6471 * .value();
6472 * // => [2, 1]
6473 */
6474 function tap(value, interceptor, thisArg) {
6475 interceptor.call(thisArg, value);
6476 return value;
6477 }
6478
6479 /**
6480 * This method is like `_.tap` except that it returns the result of `interceptor`.
6481 *
6482 * @static
6483 * @memberOf _
6484 * @category Chain
6485 * @param {*} value The value to provide to `interceptor`.
6486 * @param {Function} interceptor The function to invoke.
6487 * @param {*} [thisArg] The `this` binding of `interceptor`.
6488 * @returns {*} Returns the result of `interceptor`.
6489 * @example
6490 *
6491 * _(' abc ')
6492 * .chain()
6493 * .trim()
6494 * .thru(function(value) {
6495 * return [value];
6496 * })
6497 * .value();
6498 * // => ['abc']
6499 */
6500 function thru(value, interceptor, thisArg) {
6501 return interceptor.call(thisArg, value);
6502 }
6503
6504 /**
6505 * Enables explicit method chaining on the wrapper object.
6506 *
6507 * @name chain
6508 * @memberOf _
6509 * @category Chain
6510 * @returns {Object} Returns the new `lodash` wrapper instance.
6511 * @example
6512 *
6513 * var users = [
6514 * { 'user': 'barney', 'age': 36 },
6515 * { 'user': 'fred', 'age': 40 }
6516 * ];
6517 *
6518 * // without explicit chaining
6519 * _(users).first();
6520 * // => { 'user': 'barney', 'age': 36 }
6521 *
6522 * // with explicit chaining
6523 * _(users).chain()
6524 * .first()
6525 * .pick('user')
6526 * .value();
6527 * // => { 'user': 'barney' }
6528 */
6529 function wrapperChain() {
6530 return chain(this);
6531 }
6532
6533 /**
6534 * Executes the chained sequence and returns the wrapped result.
6535 *
6536 * @name commit
6537 * @memberOf _
6538 * @category Chain
6539 * @returns {Object} Returns the new `lodash` wrapper instance.
6540 * @example
6541 *
6542 * var array = [1, 2];
6543 * var wrapped = _(array).push(3);
6544 *
6545 * console.log(array);
6546 * // => [1, 2]
6547 *
6548 * wrapped = wrapped.commit();
6549 * console.log(array);
6550 * // => [1, 2, 3]
6551 *
6552 * wrapped.last();
6553 * // => 3
6554 *
6555 * console.log(array);
6556 * // => [1, 2, 3]
6557 */
6558 function wrapperCommit() {
6559 return new LodashWrapper(this.value(), this.__chain__);
6560 }
6561
6562 /**
6563 * Creates a new array joining a wrapped array with any additional arrays
6564 * and/or values.
6565 *
6566 * @name concat
6567 * @memberOf _
6568 * @category Chain
6569 * @param {...*} [values] The values to concatenate.
6570 * @returns {Array} Returns the new concatenated array.
6571 * @example
6572 *
6573 * var array = [1];
6574 * var wrapped = _(array).concat(2, [3], [[4]]);
6575 *
6576 * console.log(wrapped.value());
6577 * // => [1, 2, 3, [4]]
6578 *
6579 * console.log(array);
6580 * // => [1]
6581 */
6582 var wrapperConcat = restParam(function(values) {
6583 values = baseFlatten(values);
6584 return this.thru(function(array) {
6585 return arrayConcat(isArray(array) ? array : [toObject(array)], values);
6586 });
6587 });
6588
6589 /**
6590 * Creates a clone of the chained sequence planting `value` as the wrapped value.
6591 *
6592 * @name plant
6593 * @memberOf _
6594 * @category Chain
6595 * @returns {Object} Returns the new `lodash` wrapper instance.
6596 * @example
6597 *
6598 * var array = [1, 2];
6599 * var wrapped = _(array).map(function(value) {
6600 * return Math.pow(value, 2);
6601 * });
6602 *
6603 * var other = [3, 4];
6604 * var otherWrapped = wrapped.plant(other);
6605 *
6606 * otherWrapped.value();
6607 * // => [9, 16]
6608 *
6609 * wrapped.value();
6610 * // => [1, 4]
6611 */
6612 function wrapperPlant(value) {
6613 var result,
6614 parent = this;
6615
6616 while (parent instanceof baseLodash) {
6617 var clone = wrapperClone(parent);
6618 if (result) {
6619 previous.__wrapped__ = clone;
6620 } else {
6621 result = clone;
6622 }
6623 var previous = clone;
6624 parent = parent.__wrapped__;
6625 }
6626 previous.__wrapped__ = value;
6627 return result;
6628 }
6629
6630 /**
6631 * Reverses the wrapped array so the first element becomes the last, the
6632 * second element becomes the second to last, and so on.
6633 *
6634 * **Note:** This method mutates the wrapped array.
6635 *
6636 * @name reverse
6637 * @memberOf _
6638 * @category Chain
6639 * @returns {Object} Returns the new reversed `lodash` wrapper instance.
6640 * @example
6641 *
6642 * var array = [1, 2, 3];
6643 *
6644 * _(array).reverse().value()
6645 * // => [3, 2, 1]
6646 *
6647 * console.log(array);
6648 * // => [3, 2, 1]
6649 */
6650 function wrapperReverse() {
6651 var value = this.__wrapped__;
6652
6653 var interceptor = function(value) {
6654 return (wrapped && wrapped.__dir__ < 0) ? value : value.reverse();
6655 };
6656 if (value instanceof LazyWrapper) {
6657 var wrapped = value;
6658 if (this.__actions__.length) {
6659 wrapped = new LazyWrapper(this);
6660 }
6661 wrapped = wrapped.reverse();
6662 wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
6663 return new LodashWrapper(wrapped, this.__chain__);
6664 }
6665 return this.thru(interceptor);
6666 }
6667
6668 /**
6669 * Produces the result of coercing the unwrapped value to a string.
6670 *
6671 * @name toString
6672 * @memberOf _
6673 * @category Chain
6674 * @returns {string} Returns the coerced string value.
6675 * @example
6676 *
6677 * _([1, 2, 3]).toString();
6678 * // => '1,2,3'
6679 */
6680 function wrapperToString() {
6681 return (this.value() + '');
6682 }
6683
6684 /**
6685 * Executes the chained sequence to extract the unwrapped value.
6686 *
6687 * @name value
6688 * @memberOf _
6689 * @alias run, toJSON, valueOf
6690 * @category Chain
6691 * @returns {*} Returns the resolved unwrapped value.
6692 * @example
6693 *
6694 * _([1, 2, 3]).value();
6695 * // => [1, 2, 3]
6696 */
6697 function wrapperValue() {
6698 return baseWrapperValue(this.__wrapped__, this.__actions__);
6699 }
6700
6701 /*------------------------------------------------------------------------*/
6702
6703 /**
6704 * Creates an array of elements corresponding to the given keys, or indexes,
6705 * of `collection`. Keys may be specified as individual arguments or as arrays
6706 * of keys.
6707 *
6708 * @static
6709 * @memberOf _
6710 * @category Collection
6711 * @param {Array|Object|string} collection The collection to iterate over.
6712 * @param {...(number|number[]|string|string[])} [props] The property names
6713 * or indexes of elements to pick, specified individually or in arrays.
6714 * @returns {Array} Returns the new array of picked elements.
6715 * @example
6716 *
6717 * _.at(['a', 'b', 'c'], [0, 2]);
6718 * // => ['a', 'c']
6719 *
6720 * _.at(['barney', 'fred', 'pebbles'], 0, 2);
6721 * // => ['barney', 'pebbles']
6722 */
6723 var at = restParam(function(collection, props) {
6724 return baseAt(collection, baseFlatten(props));
6725 });
6726
6727 /**
6728 * Creates an object composed of keys generated from the results of running
6729 * each element of `collection` through `iteratee`. The corresponding value
6730 * of each key is the number of times the key was returned by `iteratee`.
6731 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
6732 * (value, index|key, collection).
6733 *
6734 * If a property name is provided for `iteratee` the created `_.property`
6735 * style callback returns the property value of the given element.
6736 *
6737 * If a value is also provided for `thisArg` the created `_.matchesProperty`
6738 * style callback returns `true` for elements that have a matching property
6739 * value, else `false`.
6740 *
6741 * If an object is provided for `iteratee` the created `_.matches` style
6742 * callback returns `true` for elements that have the properties of the given
6743 * object, else `false`.
6744 *
6745 * @static
6746 * @memberOf _
6747 * @category Collection
6748 * @param {Array|Object|string} collection The collection to iterate over.
6749 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
6750 * per iteration.
6751 * @param {*} [thisArg] The `this` binding of `iteratee`.
6752 * @returns {Object} Returns the composed aggregate object.
6753 * @example
6754 *
6755 * _.countBy([4.3, 6.1, 6.4], function(n) {
6756 * return Math.floor(n);
6757 * });
6758 * // => { '4': 1, '6': 2 }
6759 *
6760 * _.countBy([4.3, 6.1, 6.4], function(n) {
6761 * return this.floor(n);
6762 * }, Math);
6763 * // => { '4': 1, '6': 2 }
6764 *
6765 * _.countBy(['one', 'two', 'three'], 'length');
6766 * // => { '3': 2, '5': 1 }
6767 */
6768 var countBy = createAggregator(function(result, value, key) {
6769 hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
6770 });
6771
6772 /**
6773 * Checks if `predicate` returns truthy for **all** elements of `collection`.
6774 * The predicate is bound to `thisArg` and invoked with three arguments:
6775 * (value, index|key, collection).
6776 *
6777 * If a property name is provided for `predicate` the created `_.property`
6778 * style callback returns the property value of the given element.
6779 *
6780 * If a value is also provided for `thisArg` the created `_.matchesProperty`
6781 * style callback returns `true` for elements that have a matching property
6782 * value, else `false`.
6783 *
6784 * If an object is provided for `predicate` the created `_.matches` style
6785 * callback returns `true` for elements that have the properties of the given
6786 * object, else `false`.
6787 *
6788 * @static
6789 * @memberOf _
6790 * @alias all
6791 * @category Collection
6792 * @param {Array|Object|string} collection The collection to iterate over.
6793 * @param {Function|Object|string} [predicate=_.identity] The function invoked
6794 * per iteration.
6795 * @param {*} [thisArg] The `this` binding of `predicate`.
6796 * @returns {boolean} Returns `true` if all elements pass the predicate check,
6797 * else `false`.
6798 * @example
6799 *
6800 * _.every([true, 1, null, 'yes'], Boolean);
6801 * // => false
6802 *
6803 * var users = [
6804 * { 'user': 'barney', 'active': false },
6805 * { 'user': 'fred', 'active': false }
6806 * ];
6807 *
6808 * // using the `_.matches` callback shorthand
6809 * _.every(users, { 'user': 'barney', 'active': false });
6810 * // => false
6811 *
6812 * // using the `_.matchesProperty` callback shorthand
6813 * _.every(users, 'active', false);
6814 * // => true
6815 *
6816 * // using the `_.property` callback shorthand
6817 * _.every(users, 'active');
6818 * // => false
6819 */
6820 function every(collection, predicate, thisArg) {
6821 var func = isArray(collection) ? arrayEvery : baseEvery;
6822 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
6823 predicate = undefined;
6824 }
6825 if (typeof predicate != 'function' || thisArg !== undefined) {
6826 predicate = getCallback(predicate, thisArg, 3);
6827 }
6828 return func(collection, predicate);
6829 }
6830
6831 /**
6832 * Iterates over elements of `collection`, returning an array of all elements
6833 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
6834 * invoked with three arguments: (value, index|key, collection).
6835 *
6836 * If a property name is provided for `predicate` the created `_.property`
6837 * style callback returns the property value of the given element.
6838 *
6839 * If a value is also provided for `thisArg` the created `_.matchesProperty`
6840 * style callback returns `true` for elements that have a matching property
6841 * value, else `false`.
6842 *
6843 * If an object is provided for `predicate` the created `_.matches` style
6844 * callback returns `true` for elements that have the properties of the given
6845 * object, else `false`.
6846 *
6847 * @static
6848 * @memberOf _
6849 * @alias select
6850 * @category Collection
6851 * @param {Array|Object|string} collection The collection to iterate over.
6852 * @param {Function|Object|string} [predicate=_.identity] The function invoked
6853 * per iteration.
6854 * @param {*} [thisArg] The `this` binding of `predicate`.
6855 * @returns {Array} Returns the new filtered array.
6856 * @example
6857 *
6858 * _.filter([4, 5, 6], function(n) {
6859 * return n % 2 == 0;
6860 * });
6861 * // => [4, 6]
6862 *
6863 * var users = [
6864 * { 'user': 'barney', 'age': 36, 'active': true },
6865 * { 'user': 'fred', 'age': 40, 'active': false }
6866 * ];
6867 *
6868 * // using the `_.matches` callback shorthand
6869 * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
6870 * // => ['barney']
6871 *
6872 * // using the `_.matchesProperty` callback shorthand
6873 * _.pluck(_.filter(users, 'active', false), 'user');
6874 * // => ['fred']
6875 *
6876 * // using the `_.property` callback shorthand
6877 * _.pluck(_.filter(users, 'active'), 'user');
6878 * // => ['barney']
6879 */
6880 function filter(collection, predicate, thisArg) {
6881 var func = isArray(collection) ? arrayFilter : baseFilter;
6882 predicate = getCallback(predicate, thisArg, 3);
6883 return func(collection, predicate);
6884 }
6885
6886 /**
6887 * Iterates over elements of `collection`, returning the first element
6888 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
6889 * invoked with three arguments: (value, index|key, collection).
6890 *
6891 * If a property name is provided for `predicate` the created `_.property`
6892 * style callback returns the property value of the given element.
6893 *
6894 * If a value is also provided for `thisArg` the created `_.matchesProperty`
6895 * style callback returns `true` for elements that have a matching property
6896 * value, else `false`.
6897 *
6898 * If an object is provided for `predicate` the created `_.matches` style
6899 * callback returns `true` for elements that have the properties of the given
6900 * object, else `false`.
6901 *
6902 * @static
6903 * @memberOf _
6904 * @alias detect
6905 * @category Collection
6906 * @param {Array|Object|string} collection The collection to search.
6907 * @param {Function|Object|string} [predicate=_.identity] The function invoked
6908 * per iteration.
6909 * @param {*} [thisArg] The `this` binding of `predicate`.
6910 * @returns {*} Returns the matched element, else `undefined`.
6911 * @example
6912 *
6913 * var users = [
6914 * { 'user': 'barney', 'age': 36, 'active': true },
6915 * { 'user': 'fred', 'age': 40, 'active': false },
6916 * { 'user': 'pebbles', 'age': 1, 'active': true }
6917 * ];
6918 *
6919 * _.result(_.find(users, function(chr) {
6920 * return chr.age < 40;
6921 * }), 'user');
6922 * // => 'barney'
6923 *
6924 * // using the `_.matches` callback shorthand
6925 * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
6926 * // => 'pebbles'
6927 *
6928 * // using the `_.matchesProperty` callback shorthand
6929 * _.result(_.find(users, 'active', false), 'user');
6930 * // => 'fred'
6931 *
6932 * // using the `_.property` callback shorthand
6933 * _.result(_.find(users, 'active'), 'user');
6934 * // => 'barney'
6935 */
6936 var find = createFind(baseEach);
6937
6938 /**
6939 * This method is like `_.find` except that it iterates over elements of
6940 * `collection` from right to left.
6941 *
6942 * @static
6943 * @memberOf _
6944 * @category Collection
6945 * @param {Array|Object|string} collection The collection to search.
6946 * @param {Function|Object|string} [predicate=_.identity] The function invoked
6947 * per iteration.
6948 * @param {*} [thisArg] The `this` binding of `predicate`.
6949 * @returns {*} Returns the matched element, else `undefined`.
6950 * @example
6951 *
6952 * _.findLast([1, 2, 3, 4], function(n) {
6953 * return n % 2 == 1;
6954 * });
6955 * // => 3
6956 */
6957 var findLast = createFind(baseEachRight, true);
6958
6959 /**
6960 * Performs a deep comparison between each element in `collection` and the
6961 * source object, returning the first element that has equivalent property
6962 * values.
6963 *
6964 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
6965 * numbers, `Object` objects, regexes, and strings. Objects are compared by
6966 * their own, not inherited, enumerable properties. For comparing a single
6967 * own or inherited property value see `_.matchesProperty`.
6968 *
6969 * @static
6970 * @memberOf _
6971 * @category Collection
6972 * @param {Array|Object|string} collection The collection to search.
6973 * @param {Object} source The object of property values to match.
6974 * @returns {*} Returns the matched element, else `undefined`.
6975 * @example
6976 *
6977 * var users = [
6978 * { 'user': 'barney', 'age': 36, 'active': true },
6979 * { 'user': 'fred', 'age': 40, 'active': false }
6980 * ];
6981 *
6982 * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
6983 * // => 'barney'
6984 *
6985 * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
6986 * // => 'fred'
6987 */
6988 function findWhere(collection, source) {
6989 return find(collection, baseMatches(source));
6990 }
6991
6992 /**
6993 * Iterates over elements of `collection` invoking `iteratee` for each element.
6994 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
6995 * (value, index|key, collection). Iteratee functions may exit iteration early
6996 * by explicitly returning `false`.
6997 *
6998 * **Note:** As with other "Collections" methods, objects with a "length" property
6999 * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
7000 * may be used for object iteration.
7001 *
7002 * @static
7003 * @memberOf _
7004 * @alias each
7005 * @category Collection
7006 * @param {Array|Object|string} collection The collection to iterate over.
7007 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
7008 * @param {*} [thisArg] The `this` binding of `iteratee`.
7009 * @returns {Array|Object|string} Returns `collection`.
7010 * @example
7011 *
7012 * _([1, 2]).forEach(function(n) {
7013 * console.log(n);
7014 * }).value();
7015 * // => logs each value from left to right and returns the array
7016 *
7017 * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
7018 * console.log(n, key);
7019 * });
7020 * // => logs each value-key pair and returns the object (iteration order is not guaranteed)
7021 */
7022 var forEach = createForEach(arrayEach, baseEach);
7023
7024 /**
7025 * This method is like `_.forEach` except that it iterates over elements of
7026 * `collection` from right to left.
7027 *
7028 * @static
7029 * @memberOf _
7030 * @alias eachRight
7031 * @category Collection
7032 * @param {Array|Object|string} collection The collection to iterate over.
7033 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
7034 * @param {*} [thisArg] The `this` binding of `iteratee`.
7035 * @returns {Array|Object|string} Returns `collection`.
7036 * @example
7037 *
7038 * _([1, 2]).forEachRight(function(n) {
7039 * console.log(n);
7040 * }).value();
7041 * // => logs each value from right to left and returns the array
7042 */
7043 var forEachRight = createForEach(arrayEachRight, baseEachRight);
7044
7045 /**
7046 * Creates an object composed of keys generated from the results of running
7047 * each element of `collection` through `iteratee`. The corresponding value
7048 * of each key is an array of the elements responsible for generating the key.
7049 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
7050 * (value, index|key, collection).
7051 *
7052 * If a property name is provided for `iteratee` the created `_.property`
7053 * style callback returns the property value of the given element.
7054 *
7055 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7056 * style callback returns `true` for elements that have a matching property
7057 * value, else `false`.
7058 *
7059 * If an object is provided for `iteratee` the created `_.matches` style
7060 * callback returns `true` for elements that have the properties of the given
7061 * object, else `false`.
7062 *
7063 * @static
7064 * @memberOf _
7065 * @category Collection
7066 * @param {Array|Object|string} collection The collection to iterate over.
7067 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
7068 * per iteration.
7069 * @param {*} [thisArg] The `this` binding of `iteratee`.
7070 * @returns {Object} Returns the composed aggregate object.
7071 * @example
7072 *
7073 * _.groupBy([4.2, 6.1, 6.4], function(n) {
7074 * return Math.floor(n);
7075 * });
7076 * // => { '4': [4.2], '6': [6.1, 6.4] }
7077 *
7078 * _.groupBy([4.2, 6.1, 6.4], function(n) {
7079 * return this.floor(n);
7080 * }, Math);
7081 * // => { '4': [4.2], '6': [6.1, 6.4] }
7082 *
7083 * // using the `_.property` callback shorthand
7084 * _.groupBy(['one', 'two', 'three'], 'length');
7085 * // => { '3': ['one', 'two'], '5': ['three'] }
7086 */
7087 var groupBy = createAggregator(function(result, value, key) {
7088 if (hasOwnProperty.call(result, key)) {
7089 result[key].push(value);
7090 } else {
7091 result[key] = [value];
7092 }
7093 });
7094
7095 /**
7096 * Checks if `value` is in `collection` using
7097 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7098 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
7099 * from the end of `collection`.
7100 *
7101 * @static
7102 * @memberOf _
7103 * @alias contains, include
7104 * @category Collection
7105 * @param {Array|Object|string} collection The collection to search.
7106 * @param {*} target The value to search for.
7107 * @param {number} [fromIndex=0] The index to search from.
7108 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
7109 * @returns {boolean} Returns `true` if a matching element is found, else `false`.
7110 * @example
7111 *
7112 * _.includes([1, 2, 3], 1);
7113 * // => true
7114 *
7115 * _.includes([1, 2, 3], 1, 2);
7116 * // => false
7117 *
7118 * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
7119 * // => true
7120 *
7121 * _.includes('pebbles', 'eb');
7122 * // => true
7123 */
7124 function includes(collection, target, fromIndex, guard) {
7125 var length = collection ? getLength(collection) : 0;
7126 if (!isLength(length)) {
7127 collection = values(collection);
7128 length = collection.length;
7129 }
7130 if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
7131 fromIndex = 0;
7132 } else {
7133 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
7134 }
7135 return (typeof collection == 'string' || !isArray(collection) && isString(collection))
7136 ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
7137 : (!!length && getIndexOf(collection, target, fromIndex) > -1);
7138 }
7139
7140 /**
7141 * Creates an object composed of keys generated from the results of running
7142 * each element of `collection` through `iteratee`. The corresponding value
7143 * of each key is the last element responsible for generating the key. The
7144 * iteratee function is bound to `thisArg` and invoked with three arguments:
7145 * (value, index|key, collection).
7146 *
7147 * If a property name is provided for `iteratee` the created `_.property`
7148 * style callback returns the property value of the given element.
7149 *
7150 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7151 * style callback returns `true` for elements that have a matching property
7152 * value, else `false`.
7153 *
7154 * If an object is provided for `iteratee` the created `_.matches` style
7155 * callback returns `true` for elements that have the properties of the given
7156 * object, else `false`.
7157 *
7158 * @static
7159 * @memberOf _
7160 * @category Collection
7161 * @param {Array|Object|string} collection The collection to iterate over.
7162 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
7163 * per iteration.
7164 * @param {*} [thisArg] The `this` binding of `iteratee`.
7165 * @returns {Object} Returns the composed aggregate object.
7166 * @example
7167 *
7168 * var keyData = [
7169 * { 'dir': 'left', 'code': 97 },
7170 * { 'dir': 'right', 'code': 100 }
7171 * ];
7172 *
7173 * _.indexBy(keyData, 'dir');
7174 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
7175 *
7176 * _.indexBy(keyData, function(object) {
7177 * return String.fromCharCode(object.code);
7178 * });
7179 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
7180 *
7181 * _.indexBy(keyData, function(object) {
7182 * return this.fromCharCode(object.code);
7183 * }, String);
7184 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
7185 */
7186 var indexBy = createAggregator(function(result, value, key) {
7187 result[key] = value;
7188 });
7189
7190 /**
7191 * Invokes the method at `path` of each element in `collection`, returning
7192 * an array of the results of each invoked method. Any additional arguments
7193 * are provided to each invoked method. If `methodName` is a function it is
7194 * invoked for, and `this` bound to, each element in `collection`.
7195 *
7196 * @static
7197 * @memberOf _
7198 * @category Collection
7199 * @param {Array|Object|string} collection The collection to iterate over.
7200 * @param {Array|Function|string} path The path of the method to invoke or
7201 * the function invoked per iteration.
7202 * @param {...*} [args] The arguments to invoke the method with.
7203 * @returns {Array} Returns the array of results.
7204 * @example
7205 *
7206 * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
7207 * // => [[1, 5, 7], [1, 2, 3]]
7208 *
7209 * _.invoke([123, 456], String.prototype.split, '');
7210 * // => [['1', '2', '3'], ['4', '5', '6']]
7211 */
7212 var invoke = restParam(function(collection, path, args) {
7213 var index = -1,
7214 isFunc = typeof path == 'function',
7215 isProp = isKey(path),
7216 result = isArrayLike(collection) ? Array(collection.length) : [];
7217
7218 baseEach(collection, function(value) {
7219 var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
7220 result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
7221 });
7222 return result;
7223 });
7224
7225 /**
7226 * Creates an array of values by running each element in `collection` through
7227 * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
7228 * arguments: (value, index|key, collection).
7229 *
7230 * If a property name is provided for `iteratee` the created `_.property`
7231 * style callback returns the property value of the given element.
7232 *
7233 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7234 * style callback returns `true` for elements that have a matching property
7235 * value, else `false`.
7236 *
7237 * If an object is provided for `iteratee` the created `_.matches` style
7238 * callback returns `true` for elements that have the properties of the given
7239 * object, else `false`.
7240 *
7241 * Many lodash methods are guarded to work as iteratees for methods like
7242 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
7243 *
7244 * The guarded methods are:
7245 * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
7246 * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
7247 * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
7248 * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
7249 * `sum`, `uniq`, and `words`
7250 *
7251 * @static
7252 * @memberOf _
7253 * @alias collect
7254 * @category Collection
7255 * @param {Array|Object|string} collection The collection to iterate over.
7256 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
7257 * per iteration.
7258 * @param {*} [thisArg] The `this` binding of `iteratee`.
7259 * @returns {Array} Returns the new mapped array.
7260 * @example
7261 *
7262 * function timesThree(n) {
7263 * return n * 3;
7264 * }
7265 *
7266 * _.map([1, 2], timesThree);
7267 * // => [3, 6]
7268 *
7269 * _.map({ 'a': 1, 'b': 2 }, timesThree);
7270 * // => [3, 6] (iteration order is not guaranteed)
7271 *
7272 * var users = [
7273 * { 'user': 'barney' },
7274 * { 'user': 'fred' }
7275 * ];
7276 *
7277 * // using the `_.property` callback shorthand
7278 * _.map(users, 'user');
7279 * // => ['barney', 'fred']
7280 */
7281 function map(collection, iteratee, thisArg) {
7282 var func = isArray(collection) ? arrayMap : baseMap;
7283 iteratee = getCallback(iteratee, thisArg, 3);
7284 return func(collection, iteratee);
7285 }
7286
7287 /**
7288 * Creates an array of elements split into two groups, the first of which
7289 * contains elements `predicate` returns truthy for, while the second of which
7290 * contains elements `predicate` returns falsey for. The predicate is bound
7291 * to `thisArg` and invoked with three arguments: (value, index|key, collection).
7292 *
7293 * If a property name is provided for `predicate` the created `_.property`
7294 * style callback returns the property value of the given element.
7295 *
7296 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7297 * style callback returns `true` for elements that have a matching property
7298 * value, else `false`.
7299 *
7300 * If an object is provided for `predicate` the created `_.matches` style
7301 * callback returns `true` for elements that have the properties of the given
7302 * object, else `false`.
7303 *
7304 * @static
7305 * @memberOf _
7306 * @category Collection
7307 * @param {Array|Object|string} collection The collection to iterate over.
7308 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7309 * per iteration.
7310 * @param {*} [thisArg] The `this` binding of `predicate`.
7311 * @returns {Array} Returns the array of grouped elements.
7312 * @example
7313 *
7314 * _.partition([1, 2, 3], function(n) {
7315 * return n % 2;
7316 * });
7317 * // => [[1, 3], [2]]
7318 *
7319 * _.partition([1.2, 2.3, 3.4], function(n) {
7320 * return this.floor(n) % 2;
7321 * }, Math);
7322 * // => [[1.2, 3.4], [2.3]]
7323 *
7324 * var users = [
7325 * { 'user': 'barney', 'age': 36, 'active': false },
7326 * { 'user': 'fred', 'age': 40, 'active': true },
7327 * { 'user': 'pebbles', 'age': 1, 'active': false }
7328 * ];
7329 *
7330 * var mapper = function(array) {
7331 * return _.pluck(array, 'user');
7332 * };
7333 *
7334 * // using the `_.matches` callback shorthand
7335 * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
7336 * // => [['pebbles'], ['barney', 'fred']]
7337 *
7338 * // using the `_.matchesProperty` callback shorthand
7339 * _.map(_.partition(users, 'active', false), mapper);
7340 * // => [['barney', 'pebbles'], ['fred']]
7341 *
7342 * // using the `_.property` callback shorthand
7343 * _.map(_.partition(users, 'active'), mapper);
7344 * // => [['fred'], ['barney', 'pebbles']]
7345 */
7346 var partition = createAggregator(function(result, value, key) {
7347 result[key ? 0 : 1].push(value);
7348 }, function() { return [[], []]; });
7349
7350 /**
7351 * Gets the property value of `path` from all elements in `collection`.
7352 *
7353 * @static
7354 * @memberOf _
7355 * @category Collection
7356 * @param {Array|Object|string} collection The collection to iterate over.
7357 * @param {Array|string} path The path of the property to pluck.
7358 * @returns {Array} Returns the property values.
7359 * @example
7360 *
7361 * var users = [
7362 * { 'user': 'barney', 'age': 36 },
7363 * { 'user': 'fred', 'age': 40 }
7364 * ];
7365 *
7366 * _.pluck(users, 'user');
7367 * // => ['barney', 'fred']
7368 *
7369 * var userIndex = _.indexBy(users, 'user');
7370 * _.pluck(userIndex, 'age');
7371 * // => [36, 40] (iteration order is not guaranteed)
7372 */
7373 function pluck(collection, path) {
7374 return map(collection, property(path));
7375 }
7376
7377 /**
7378 * Reduces `collection` to a value which is the accumulated result of running
7379 * each element in `collection` through `iteratee`, where each successive
7380 * invocation is supplied the return value of the previous. If `accumulator`
7381 * is not provided the first element of `collection` is used as the initial
7382 * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
7383 * (accumulator, value, index|key, collection).
7384 *
7385 * Many lodash methods are guarded to work as iteratees for methods like
7386 * `_.reduce`, `_.reduceRight`, and `_.transform`.
7387 *
7388 * The guarded methods are:
7389 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
7390 * and `sortByOrder`
7391 *
7392 * @static
7393 * @memberOf _
7394 * @alias foldl, inject
7395 * @category Collection
7396 * @param {Array|Object|string} collection The collection to iterate over.
7397 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
7398 * @param {*} [accumulator] The initial value.
7399 * @param {*} [thisArg] The `this` binding of `iteratee`.
7400 * @returns {*} Returns the accumulated value.
7401 * @example
7402 *
7403 * _.reduce([1, 2], function(total, n) {
7404 * return total + n;
7405 * });
7406 * // => 3
7407 *
7408 * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
7409 * result[key] = n * 3;
7410 * return result;
7411 * }, {});
7412 * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
7413 */
7414 var reduce = createReduce(arrayReduce, baseEach);
7415
7416 /**
7417 * This method is like `_.reduce` except that it iterates over elements of
7418 * `collection` from right to left.
7419 *
7420 * @static
7421 * @memberOf _
7422 * @alias foldr
7423 * @category Collection
7424 * @param {Array|Object|string} collection The collection to iterate over.
7425 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
7426 * @param {*} [accumulator] The initial value.
7427 * @param {*} [thisArg] The `this` binding of `iteratee`.
7428 * @returns {*} Returns the accumulated value.
7429 * @example
7430 *
7431 * var array = [[0, 1], [2, 3], [4, 5]];
7432 *
7433 * _.reduceRight(array, function(flattened, other) {
7434 * return flattened.concat(other);
7435 * }, []);
7436 * // => [4, 5, 2, 3, 0, 1]
7437 */
7438 var reduceRight = createReduce(arrayReduceRight, baseEachRight);
7439
7440 /**
7441 * The opposite of `_.filter`; this method returns the elements of `collection`
7442 * that `predicate` does **not** return truthy for.
7443 *
7444 * @static
7445 * @memberOf _
7446 * @category Collection
7447 * @param {Array|Object|string} collection The collection to iterate over.
7448 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7449 * per iteration.
7450 * @param {*} [thisArg] The `this` binding of `predicate`.
7451 * @returns {Array} Returns the new filtered array.
7452 * @example
7453 *
7454 * _.reject([1, 2, 3, 4], function(n) {
7455 * return n % 2 == 0;
7456 * });
7457 * // => [1, 3]
7458 *
7459 * var users = [
7460 * { 'user': 'barney', 'age': 36, 'active': false },
7461 * { 'user': 'fred', 'age': 40, 'active': true }
7462 * ];
7463 *
7464 * // using the `_.matches` callback shorthand
7465 * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
7466 * // => ['barney']
7467 *
7468 * // using the `_.matchesProperty` callback shorthand
7469 * _.pluck(_.reject(users, 'active', false), 'user');
7470 * // => ['fred']
7471 *
7472 * // using the `_.property` callback shorthand
7473 * _.pluck(_.reject(users, 'active'), 'user');
7474 * // => ['barney']
7475 */
7476 function reject(collection, predicate, thisArg) {
7477 var func = isArray(collection) ? arrayFilter : baseFilter;
7478 predicate = getCallback(predicate, thisArg, 3);
7479 return func(collection, function(value, index, collection) {
7480 return !predicate(value, index, collection);
7481 });
7482 }
7483
7484 /**
7485 * Gets a random element or `n` random elements from a collection.
7486 *
7487 * @static
7488 * @memberOf _
7489 * @category Collection
7490 * @param {Array|Object|string} collection The collection to sample.
7491 * @param {number} [n] The number of elements to sample.
7492 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
7493 * @returns {*} Returns the random sample(s).
7494 * @example
7495 *
7496 * _.sample([1, 2, 3, 4]);
7497 * // => 2
7498 *
7499 * _.sample([1, 2, 3, 4], 2);
7500 * // => [3, 1]
7501 */
7502 function sample(collection, n, guard) {
7503 if (guard ? isIterateeCall(collection, n, guard) : n == null) {
7504 collection = toIterable(collection);
7505 var length = collection.length;
7506 return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
7507 }
7508 var index = -1,
7509 result = toArray(collection),
7510 length = result.length,
7511 lastIndex = length - 1;
7512
7513 n = nativeMin(n < 0 ? 0 : (+n || 0), length);
7514 while (++index < n) {
7515 var rand = baseRandom(index, lastIndex),
7516 value = result[rand];
7517
7518 result[rand] = result[index];
7519 result[index] = value;
7520 }
7521 result.length = n;
7522 return result;
7523 }
7524
7525 /**
7526 * Creates an array of shuffled values, using a version of the
7527 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
7528 *
7529 * @static
7530 * @memberOf _
7531 * @category Collection
7532 * @param {Array|Object|string} collection The collection to shuffle.
7533 * @returns {Array} Returns the new shuffled array.
7534 * @example
7535 *
7536 * _.shuffle([1, 2, 3, 4]);
7537 * // => [4, 1, 3, 2]
7538 */
7539 function shuffle(collection) {
7540 return sample(collection, POSITIVE_INFINITY);
7541 }
7542
7543 /**
7544 * Gets the size of `collection` by returning its length for array-like
7545 * values or the number of own enumerable properties for objects.
7546 *
7547 * @static
7548 * @memberOf _
7549 * @category Collection
7550 * @param {Array|Object|string} collection The collection to inspect.
7551 * @returns {number} Returns the size of `collection`.
7552 * @example
7553 *
7554 * _.size([1, 2, 3]);
7555 * // => 3
7556 *
7557 * _.size({ 'a': 1, 'b': 2 });
7558 * // => 2
7559 *
7560 * _.size('pebbles');
7561 * // => 7
7562 */
7563 function size(collection) {
7564 var length = collection ? getLength(collection) : 0;
7565 return isLength(length) ? length : keys(collection).length;
7566 }
7567
7568 /**
7569 * Checks if `predicate` returns truthy for **any** element of `collection`.
7570 * The function returns as soon as it finds a passing value and does not iterate
7571 * over the entire collection. The predicate is bound to `thisArg` and invoked
7572 * with three arguments: (value, index|key, collection).
7573 *
7574 * If a property name is provided for `predicate` the created `_.property`
7575 * style callback returns the property value of the given element.
7576 *
7577 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7578 * style callback returns `true` for elements that have a matching property
7579 * value, else `false`.
7580 *
7581 * If an object is provided for `predicate` the created `_.matches` style
7582 * callback returns `true` for elements that have the properties of the given
7583 * object, else `false`.
7584 *
7585 * @static
7586 * @memberOf _
7587 * @alias any
7588 * @category Collection
7589 * @param {Array|Object|string} collection The collection to iterate over.
7590 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7591 * per iteration.
7592 * @param {*} [thisArg] The `this` binding of `predicate`.
7593 * @returns {boolean} Returns `true` if any element passes the predicate check,
7594 * else `false`.
7595 * @example
7596 *
7597 * _.some([null, 0, 'yes', false], Boolean);
7598 * // => true
7599 *
7600 * var users = [
7601 * { 'user': 'barney', 'active': true },
7602 * { 'user': 'fred', 'active': false }
7603 * ];
7604 *
7605 * // using the `_.matches` callback shorthand
7606 * _.some(users, { 'user': 'barney', 'active': false });
7607 * // => false
7608 *
7609 * // using the `_.matchesProperty` callback shorthand
7610 * _.some(users, 'active', false);
7611 * // => true
7612 *
7613 * // using the `_.property` callback shorthand
7614 * _.some(users, 'active');
7615 * // => true
7616 */
7617 function some(collection, predicate, thisArg) {
7618 var func = isArray(collection) ? arraySome : baseSome;
7619 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
7620 predicate = undefined;
7621 }
7622 if (typeof predicate != 'function' || thisArg !== undefined) {
7623 predicate = getCallback(predicate, thisArg, 3);
7624 }
7625 return func(collection, predicate);
7626 }
7627
7628 /**
7629 * Creates an array of elements, sorted in ascending order by the results of
7630 * running each element in a collection through `iteratee`. This method performs
7631 * a stable sort, that is, it preserves the original sort order of equal elements.
7632 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
7633 * (value, index|key, collection).
7634 *
7635 * If a property name is provided for `iteratee` the created `_.property`
7636 * style callback returns the property value of the given element.
7637 *
7638 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7639 * style callback returns `true` for elements that have a matching property
7640 * value, else `false`.
7641 *
7642 * If an object is provided for `iteratee` the created `_.matches` style
7643 * callback returns `true` for elements that have the properties of the given
7644 * object, else `false`.
7645 *
7646 * @static
7647 * @memberOf _
7648 * @category Collection
7649 * @param {Array|Object|string} collection The collection to iterate over.
7650 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
7651 * per iteration.
7652 * @param {*} [thisArg] The `this` binding of `iteratee`.
7653 * @returns {Array} Returns the new sorted array.
7654 * @example
7655 *
7656 * _.sortBy([1, 2, 3], function(n) {
7657 * return Math.sin(n);
7658 * });
7659 * // => [3, 1, 2]
7660 *
7661 * _.sortBy([1, 2, 3], function(n) {
7662 * return this.sin(n);
7663 * }, Math);
7664 * // => [3, 1, 2]
7665 *
7666 * var users = [
7667 * { 'user': 'fred' },
7668 * { 'user': 'pebbles' },
7669 * { 'user': 'barney' }
7670 * ];
7671 *
7672 * // using the `_.property` callback shorthand
7673 * _.pluck(_.sortBy(users, 'user'), 'user');
7674 * // => ['barney', 'fred', 'pebbles']
7675 */
7676 function sortBy(collection, iteratee, thisArg) {
7677 if (collection == null) {
7678 return [];
7679 }
7680 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
7681 iteratee = undefined;
7682 }
7683 var index = -1;
7684 iteratee = getCallback(iteratee, thisArg, 3);
7685
7686 var result = baseMap(collection, function(value, key, collection) {
7687 return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
7688 });
7689 return baseSortBy(result, compareAscending);
7690 }
7691
7692 /**
7693 * This method is like `_.sortBy` except that it can sort by multiple iteratees
7694 * or property names.
7695 *
7696 * If a property name is provided for an iteratee the created `_.property`
7697 * style callback returns the property value of the given element.
7698 *
7699 * If an object is provided for an iteratee the created `_.matches` style
7700 * callback returns `true` for elements that have the properties of the given
7701 * object, else `false`.
7702 *
7703 * @static
7704 * @memberOf _
7705 * @category Collection
7706 * @param {Array|Object|string} collection The collection to iterate over.
7707 * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
7708 * The iteratees to sort by, specified as individual values or arrays of values.
7709 * @returns {Array} Returns the new sorted array.
7710 * @example
7711 *
7712 * var users = [
7713 * { 'user': 'fred', 'age': 48 },
7714 * { 'user': 'barney', 'age': 36 },
7715 * { 'user': 'fred', 'age': 42 },
7716 * { 'user': 'barney', 'age': 34 }
7717 * ];
7718 *
7719 * _.map(_.sortByAll(users, ['user', 'age']), _.values);
7720 * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
7721 *
7722 * _.map(_.sortByAll(users, 'user', function(chr) {
7723 * return Math.floor(chr.age / 10);
7724 * }), _.values);
7725 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
7726 */
7727 var sortByAll = restParam(function(collection, iteratees) {
7728 if (collection == null) {
7729 return [];
7730 }
7731 var guard = iteratees[2];
7732 if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
7733 iteratees.length = 1;
7734 }
7735 return baseSortByOrder(collection, baseFlatten(iteratees), []);
7736 });
7737
7738 /**
7739 * This method is like `_.sortByAll` except that it allows specifying the
7740 * sort orders of the iteratees to sort by. If `orders` is unspecified, all
7741 * values are sorted in ascending order. Otherwise, a value is sorted in
7742 * ascending order if its corresponding order is "asc", and descending if "desc".
7743 *
7744 * If a property name is provided for an iteratee the created `_.property`
7745 * style callback returns the property value of the given element.
7746 *
7747 * If an object is provided for an iteratee the created `_.matches` style
7748 * callback returns `true` for elements that have the properties of the given
7749 * object, else `false`.
7750 *
7751 * @static
7752 * @memberOf _
7753 * @category Collection
7754 * @param {Array|Object|string} collection The collection to iterate over.
7755 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
7756 * @param {boolean[]} [orders] The sort orders of `iteratees`.
7757 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
7758 * @returns {Array} Returns the new sorted array.
7759 * @example
7760 *
7761 * var users = [
7762 * { 'user': 'fred', 'age': 48 },
7763 * { 'user': 'barney', 'age': 34 },
7764 * { 'user': 'fred', 'age': 42 },
7765 * { 'user': 'barney', 'age': 36 }
7766 * ];
7767 *
7768 * // sort by `user` in ascending order and by `age` in descending order
7769 * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
7770 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
7771 */
7772 function sortByOrder(collection, iteratees, orders, guard) {
7773 if (collection == null) {
7774 return [];
7775 }
7776 if (guard && isIterateeCall(iteratees, orders, guard)) {
7777 orders = undefined;
7778 }
7779 if (!isArray(iteratees)) {
7780 iteratees = iteratees == null ? [] : [iteratees];
7781 }
7782 if (!isArray(orders)) {
7783 orders = orders == null ? [] : [orders];
7784 }
7785 return baseSortByOrder(collection, iteratees, orders);
7786 }
7787
7788 /**
7789 * Performs a deep comparison between each element in `collection` and the
7790 * source object, returning an array of all elements that have equivalent
7791 * property values.
7792 *
7793 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
7794 * numbers, `Object` objects, regexes, and strings. Objects are compared by
7795 * their own, not inherited, enumerable properties. For comparing a single
7796 * own or inherited property value see `_.matchesProperty`.
7797 *
7798 * @static
7799 * @memberOf _
7800 * @category Collection
7801 * @param {Array|Object|string} collection The collection to search.
7802 * @param {Object} source The object of property values to match.
7803 * @returns {Array} Returns the new filtered array.
7804 * @example
7805 *
7806 * var users = [
7807 * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
7808 * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
7809 * ];
7810 *
7811 * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
7812 * // => ['barney']
7813 *
7814 * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
7815 * // => ['fred']
7816 */
7817 function where(collection, source) {
7818 return filter(collection, baseMatches(source));
7819 }
7820
7821 /*------------------------------------------------------------------------*/
7822
7823 /**
7824 * Gets the number of milliseconds that have elapsed since the Unix epoch
7825 * (1 January 1970 00:00:00 UTC).
7826 *
7827 * @static
7828 * @memberOf _
7829 * @category Date
7830 * @example
7831 *
7832 * _.defer(function(stamp) {
7833 * console.log(_.now() - stamp);
7834 * }, _.now());
7835 * // => logs the number of milliseconds it took for the deferred function to be invoked
7836 */
7837 var now = nativeNow || function() {
7838 return new Date().getTime();
7839 };
7840
7841 /*------------------------------------------------------------------------*/
7842
7843 /**
7844 * The opposite of `_.before`; this method creates a function that invokes
7845 * `func` once it is called `n` or more times.
7846 *
7847 * @static
7848 * @memberOf _
7849 * @category Function
7850 * @param {number} n The number of calls before `func` is invoked.
7851 * @param {Function} func The function to restrict.
7852 * @returns {Function} Returns the new restricted function.
7853 * @example
7854 *
7855 * var saves = ['profile', 'settings'];
7856 *
7857 * var done = _.after(saves.length, function() {
7858 * console.log('done saving!');
7859 * });
7860 *
7861 * _.forEach(saves, function(type) {
7862 * asyncSave({ 'type': type, 'complete': done });
7863 * });
7864 * // => logs 'done saving!' after the two async saves have completed
7865 */
7866 function after(n, func) {
7867 if (typeof func != 'function') {
7868 if (typeof n == 'function') {
7869 var temp = n;
7870 n = func;
7871 func = temp;
7872 } else {
7873 throw new TypeError(FUNC_ERROR_TEXT);
7874 }
7875 }
7876 n = nativeIsFinite(n = +n) ? n : 0;
7877 return function() {
7878 if (--n < 1) {
7879 return func.apply(this, arguments);
7880 }
7881 };
7882 }
7883
7884 /**
7885 * Creates a function that accepts up to `n` arguments ignoring any
7886 * additional arguments.
7887 *
7888 * @static
7889 * @memberOf _
7890 * @category Function
7891 * @param {Function} func The function to cap arguments for.
7892 * @param {number} [n=func.length] The arity cap.
7893 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
7894 * @returns {Function} Returns the new function.
7895 * @example
7896 *
7897 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
7898 * // => [6, 8, 10]
7899 */
7900 function ary(func, n, guard) {
7901 if (guard && isIterateeCall(func, n, guard)) {
7902 n = undefined;
7903 }
7904 n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
7905 return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
7906 }
7907
7908 /**
7909 * Creates a function that invokes `func`, with the `this` binding and arguments
7910 * of the created function, while it is called less than `n` times. Subsequent
7911 * calls to the created function return the result of the last `func` invocation.
7912 *
7913 * @static
7914 * @memberOf _
7915 * @category Function
7916 * @param {number} n The number of calls at which `func` is no longer invoked.
7917 * @param {Function} func The function to restrict.
7918 * @returns {Function} Returns the new restricted function.
7919 * @example
7920 *
7921 * jQuery('#add').on('click', _.before(5, addContactToList));
7922 * // => allows adding up to 4 contacts to the list
7923 */
7924 function before(n, func) {
7925 var result;
7926 if (typeof func != 'function') {
7927 if (typeof n == 'function') {
7928 var temp = n;
7929 n = func;
7930 func = temp;
7931 } else {
7932 throw new TypeError(FUNC_ERROR_TEXT);
7933 }
7934 }
7935 return function() {
7936 if (--n > 0) {
7937 result = func.apply(this, arguments);
7938 }
7939 if (n <= 1) {
7940 func = undefined;
7941 }
7942 return result;
7943 };
7944 }
7945
7946 /**
7947 * Creates a function that invokes `func` with the `this` binding of `thisArg`
7948 * and prepends any additional `_.bind` arguments to those provided to the
7949 * bound function.
7950 *
7951 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
7952 * may be used as a placeholder for partially applied arguments.
7953 *
7954 * **Note:** Unlike native `Function#bind` this method does not set the "length"
7955 * property of bound functions.
7956 *
7957 * @static
7958 * @memberOf _
7959 * @category Function
7960 * @param {Function} func The function to bind.
7961 * @param {*} thisArg The `this` binding of `func`.
7962 * @param {...*} [partials] The arguments to be partially applied.
7963 * @returns {Function} Returns the new bound function.
7964 * @example
7965 *
7966 * var greet = function(greeting, punctuation) {
7967 * return greeting + ' ' + this.user + punctuation;
7968 * };
7969 *
7970 * var object = { 'user': 'fred' };
7971 *
7972 * var bound = _.bind(greet, object, 'hi');
7973 * bound('!');
7974 * // => 'hi fred!'
7975 *
7976 * // using placeholders
7977 * var bound = _.bind(greet, object, _, '!');
7978 * bound('hi');
7979 * // => 'hi fred!'
7980 */
7981 var bind = restParam(function(func, thisArg, partials) {
7982 var bitmask = BIND_FLAG;
7983 if (partials.length) {
7984 var holders = replaceHolders(partials, bind.placeholder);
7985 bitmask |= PARTIAL_FLAG;
7986 }
7987 return createWrapper(func, bitmask, thisArg, partials, holders);
7988 });
7989
7990 /**
7991 * Binds methods of an object to the object itself, overwriting the existing
7992 * method. Method names may be specified as individual arguments or as arrays
7993 * of method names. If no method names are provided all enumerable function
7994 * properties, own and inherited, of `object` are bound.
7995 *
7996 * **Note:** This method does not set the "length" property of bound functions.
7997 *
7998 * @static
7999 * @memberOf _
8000 * @category Function
8001 * @param {Object} object The object to bind and assign the bound methods to.
8002 * @param {...(string|string[])} [methodNames] The object method names to bind,
8003 * specified as individual method names or arrays of method names.
8004 * @returns {Object} Returns `object`.
8005 * @example
8006 *
8007 * var view = {
8008 * 'label': 'docs',
8009 * 'onClick': function() {
8010 * console.log('clicked ' + this.label);
8011 * }
8012 * };
8013 *
8014 * _.bindAll(view);
8015 * jQuery('#docs').on('click', view.onClick);
8016 * // => logs 'clicked docs' when the element is clicked
8017 */
8018 var bindAll = restParam(function(object, methodNames) {
8019 methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
8020
8021 var index = -1,
8022 length = methodNames.length;
8023
8024 while (++index < length) {
8025 var key = methodNames[index];
8026 object[key] = createWrapper(object[key], BIND_FLAG, object);
8027 }
8028 return object;
8029 });
8030
8031 /**
8032 * Creates a function that invokes the method at `object[key]` and prepends
8033 * any additional `_.bindKey` arguments to those provided to the bound function.
8034 *
8035 * This method differs from `_.bind` by allowing bound functions to reference
8036 * methods that may be redefined or don't yet exist.
8037 * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
8038 * for more details.
8039 *
8040 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
8041 * builds, may be used as a placeholder for partially applied arguments.
8042 *
8043 * @static
8044 * @memberOf _
8045 * @category Function
8046 * @param {Object} object The object the method belongs to.
8047 * @param {string} key The key of the method.
8048 * @param {...*} [partials] The arguments to be partially applied.
8049 * @returns {Function} Returns the new bound function.
8050 * @example
8051 *
8052 * var object = {
8053 * 'user': 'fred',
8054 * 'greet': function(greeting, punctuation) {
8055 * return greeting + ' ' + this.user + punctuation;
8056 * }
8057 * };
8058 *
8059 * var bound = _.bindKey(object, 'greet', 'hi');
8060 * bound('!');
8061 * // => 'hi fred!'
8062 *
8063 * object.greet = function(greeting, punctuation) {
8064 * return greeting + 'ya ' + this.user + punctuation;
8065 * };
8066 *
8067 * bound('!');
8068 * // => 'hiya fred!'
8069 *
8070 * // using placeholders
8071 * var bound = _.bindKey(object, 'greet', _, '!');
8072 * bound('hi');
8073 * // => 'hiya fred!'
8074 */
8075 var bindKey = restParam(function(object, key, partials) {
8076 var bitmask = BIND_FLAG | BIND_KEY_FLAG;
8077 if (partials.length) {
8078 var holders = replaceHolders(partials, bindKey.placeholder);
8079 bitmask |= PARTIAL_FLAG;
8080 }
8081 return createWrapper(key, bitmask, object, partials, holders);
8082 });
8083
8084 /**
8085 * Creates a function that accepts one or more arguments of `func` that when
8086 * called either invokes `func` returning its result, if all `func` arguments
8087 * have been provided, or returns a function that accepts one or more of the
8088 * remaining `func` arguments, and so on. The arity of `func` may be specified
8089 * if `func.length` is not sufficient.
8090 *
8091 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
8092 * may be used as a placeholder for provided arguments.
8093 *
8094 * **Note:** This method does not set the "length" property of curried functions.
8095 *
8096 * @static
8097 * @memberOf _
8098 * @category Function
8099 * @param {Function} func The function to curry.
8100 * @param {number} [arity=func.length] The arity of `func`.
8101 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
8102 * @returns {Function} Returns the new curried function.
8103 * @example
8104 *
8105 * var abc = function(a, b, c) {
8106 * return [a, b, c];
8107 * };
8108 *
8109 * var curried = _.curry(abc);
8110 *
8111 * curried(1)(2)(3);
8112 * // => [1, 2, 3]
8113 *
8114 * curried(1, 2)(3);
8115 * // => [1, 2, 3]
8116 *
8117 * curried(1, 2, 3);
8118 * // => [1, 2, 3]
8119 *
8120 * // using placeholders
8121 * curried(1)(_, 3)(2);
8122 * // => [1, 2, 3]
8123 */
8124 var curry = createCurry(CURRY_FLAG);
8125
8126 /**
8127 * This method is like `_.curry` except that arguments are applied to `func`
8128 * in the manner of `_.partialRight` instead of `_.partial`.
8129 *
8130 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
8131 * builds, may be used as a placeholder for provided arguments.
8132 *
8133 * **Note:** This method does not set the "length" property of curried functions.
8134 *
8135 * @static
8136 * @memberOf _
8137 * @category Function
8138 * @param {Function} func The function to curry.
8139 * @param {number} [arity=func.length] The arity of `func`.
8140 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
8141 * @returns {Function} Returns the new curried function.
8142 * @example
8143 *
8144 * var abc = function(a, b, c) {
8145 * return [a, b, c];
8146 * };
8147 *
8148 * var curried = _.curryRight(abc);
8149 *
8150 * curried(3)(2)(1);
8151 * // => [1, 2, 3]
8152 *
8153 * curried(2, 3)(1);
8154 * // => [1, 2, 3]
8155 *
8156 * curried(1, 2, 3);
8157 * // => [1, 2, 3]
8158 *
8159 * // using placeholders
8160 * curried(3)(1, _)(2);
8161 * // => [1, 2, 3]
8162 */
8163 var curryRight = createCurry(CURRY_RIGHT_FLAG);
8164
8165 /**
8166 * Creates a debounced function that delays invoking `func` until after `wait`
8167 * milliseconds have elapsed since the last time the debounced function was
8168 * invoked. The debounced function comes with a `cancel` method to cancel
8169 * delayed invocations. Provide an options object to indicate that `func`
8170 * should be invoked on the leading and/or trailing edge of the `wait` timeout.
8171 * Subsequent calls to the debounced function return the result of the last
8172 * `func` invocation.
8173 *
8174 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
8175 * on the trailing edge of the timeout only if the the debounced function is
8176 * invoked more than once during the `wait` timeout.
8177 *
8178 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
8179 * for details over the differences between `_.debounce` and `_.throttle`.
8180 *
8181 * @static
8182 * @memberOf _
8183 * @category Function
8184 * @param {Function} func The function to debounce.
8185 * @param {number} [wait=0] The number of milliseconds to delay.
8186 * @param {Object} [options] The options object.
8187 * @param {boolean} [options.leading=false] Specify invoking on the leading
8188 * edge of the timeout.
8189 * @param {number} [options.maxWait] The maximum time `func` is allowed to be
8190 * delayed before it is invoked.
8191 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
8192 * edge of the timeout.
8193 * @returns {Function} Returns the new debounced function.
8194 * @example
8195 *
8196 * // avoid costly calculations while the window size is in flux
8197 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
8198 *
8199 * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
8200 * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
8201 * 'leading': true,
8202 * 'trailing': false
8203 * }));
8204 *
8205 * // ensure `batchLog` is invoked once after 1 second of debounced calls
8206 * var source = new EventSource('/stream');
8207 * jQuery(source).on('message', _.debounce(batchLog, 250, {
8208 * 'maxWait': 1000
8209 * }));
8210 *
8211 * // cancel a debounced call
8212 * var todoChanges = _.debounce(batchLog, 1000);
8213 * Object.observe(models.todo, todoChanges);
8214 *
8215 * Object.observe(models, function(changes) {
8216 * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
8217 * todoChanges.cancel();
8218 * }
8219 * }, ['delete']);
8220 *
8221 * // ...at some point `models.todo` is changed
8222 * models.todo.completed = true;
8223 *
8224 * // ...before 1 second has passed `models.todo` is deleted
8225 * // which cancels the debounced `todoChanges` call
8226 * delete models.todo;
8227 */
8228 function debounce(func, wait, options) {
8229 var args,
8230 maxTimeoutId,
8231 result,
8232 stamp,
8233 thisArg,
8234 timeoutId,
8235 trailingCall,
8236 lastCalled = 0,
8237 maxWait = false,
8238 trailing = true;
8239
8240 if (typeof func != 'function') {
8241 throw new TypeError(FUNC_ERROR_TEXT);
8242 }
8243 wait = wait < 0 ? 0 : (+wait || 0);
8244 if (options === true) {
8245 var leading = true;
8246 trailing = false;
8247 } else if (isObject(options)) {
8248 leading = !!options.leading;
8249 maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
8250 trailing = 'trailing' in options ? !!options.trailing : trailing;
8251 }
8252
8253 function cancel() {
8254 if (timeoutId) {
8255 clearTimeout(timeoutId);
8256 }
8257 if (maxTimeoutId) {
8258 clearTimeout(maxTimeoutId);
8259 }
8260 lastCalled = 0;
8261 maxTimeoutId = timeoutId = trailingCall = undefined;
8262 }
8263
8264 function complete(isCalled, id) {
8265 if (id) {
8266 clearTimeout(id);
8267 }
8268 maxTimeoutId = timeoutId = trailingCall = undefined;
8269 if (isCalled) {
8270 lastCalled = now();
8271 result = func.apply(thisArg, args);
8272 if (!timeoutId && !maxTimeoutId) {
8273 args = thisArg = undefined;
8274 }
8275 }
8276 }
8277
8278 function delayed() {
8279 var remaining = wait - (now() - stamp);
8280 if (remaining <= 0 || remaining > wait) {
8281 complete(trailingCall, maxTimeoutId);
8282 } else {
8283 timeoutId = setTimeout(delayed, remaining);
8284 }
8285 }
8286
8287 function maxDelayed() {
8288 complete(trailing, timeoutId);
8289 }
8290
8291 function debounced() {
8292 args = arguments;
8293 stamp = now();
8294 thisArg = this;
8295 trailingCall = trailing && (timeoutId || !leading);
8296
8297 if (maxWait === false) {
8298 var leadingCall = leading && !timeoutId;
8299 } else {
8300 if (!maxTimeoutId && !leading) {
8301 lastCalled = stamp;
8302 }
8303 var remaining = maxWait - (stamp - lastCalled),
8304 isCalled = remaining <= 0 || remaining > maxWait;
8305
8306 if (isCalled) {
8307 if (maxTimeoutId) {
8308 maxTimeoutId = clearTimeout(maxTimeoutId);
8309 }
8310 lastCalled = stamp;
8311 result = func.apply(thisArg, args);
8312 }
8313 else if (!maxTimeoutId) {
8314 maxTimeoutId = setTimeout(maxDelayed, remaining);
8315 }
8316 }
8317 if (isCalled && timeoutId) {
8318 timeoutId = clearTimeout(timeoutId);
8319 }
8320 else if (!timeoutId && wait !== maxWait) {
8321 timeoutId = setTimeout(delayed, wait);
8322 }
8323 if (leadingCall) {
8324 isCalled = true;
8325 result = func.apply(thisArg, args);
8326 }
8327 if (isCalled && !timeoutId && !maxTimeoutId) {
8328 args = thisArg = undefined;
8329 }
8330 return result;
8331 }
8332 debounced.cancel = cancel;
8333 return debounced;
8334 }
8335
8336 /**
8337 * Defers invoking the `func` until the current call stack has cleared. Any
8338 * additional arguments are provided to `func` when it is invoked.
8339 *
8340 * @static
8341 * @memberOf _
8342 * @category Function
8343 * @param {Function} func The function to defer.
8344 * @param {...*} [args] The arguments to invoke the function with.
8345 * @returns {number} Returns the timer id.
8346 * @example
8347 *
8348 * _.defer(function(text) {
8349 * console.log(text);
8350 * }, 'deferred');
8351 * // logs 'deferred' after one or more milliseconds
8352 */
8353 var defer = restParam(function(func, args) {
8354 return baseDelay(func, 1, args);
8355 });
8356
8357 /**
8358 * Invokes `func` after `wait` milliseconds. Any additional arguments are
8359 * provided to `func` when it is invoked.
8360 *
8361 * @static
8362 * @memberOf _
8363 * @category Function
8364 * @param {Function} func The function to delay.
8365 * @param {number} wait The number of milliseconds to delay invocation.
8366 * @param {...*} [args] The arguments to invoke the function with.
8367 * @returns {number} Returns the timer id.
8368 * @example
8369 *
8370 * _.delay(function(text) {
8371 * console.log(text);
8372 * }, 1000, 'later');
8373 * // => logs 'later' after one second
8374 */
8375 var delay = restParam(function(func, wait, args) {
8376 return baseDelay(func, wait, args);
8377 });
8378
8379 /**
8380 * Creates a function that returns the result of invoking the provided
8381 * functions with the `this` binding of the created function, where each
8382 * successive invocation is supplied the return value of the previous.
8383 *
8384 * @static
8385 * @memberOf _
8386 * @category Function
8387 * @param {...Function} [funcs] Functions to invoke.
8388 * @returns {Function} Returns the new function.
8389 * @example
8390 *
8391 * function square(n) {
8392 * return n * n;
8393 * }
8394 *
8395 * var addSquare = _.flow(_.add, square);
8396 * addSquare(1, 2);
8397 * // => 9
8398 */
8399 var flow = createFlow();
8400
8401 /**
8402 * This method is like `_.flow` except that it creates a function that
8403 * invokes the provided functions from right to left.
8404 *
8405 * @static
8406 * @memberOf _
8407 * @alias backflow, compose
8408 * @category Function
8409 * @param {...Function} [funcs] Functions to invoke.
8410 * @returns {Function} Returns the new function.
8411 * @example
8412 *
8413 * function square(n) {
8414 * return n * n;
8415 * }
8416 *
8417 * var addSquare = _.flowRight(square, _.add);
8418 * addSquare(1, 2);
8419 * // => 9
8420 */
8421 var flowRight = createFlow(true);
8422
8423 /**
8424 * Creates a function that memoizes the result of `func`. If `resolver` is
8425 * provided it determines the cache key for storing the result based on the
8426 * arguments provided to the memoized function. By default, the first argument
8427 * provided to the memoized function is coerced to a string and used as the
8428 * cache key. The `func` is invoked with the `this` binding of the memoized
8429 * function.
8430 *
8431 * **Note:** The cache is exposed as the `cache` property on the memoized
8432 * function. Its creation may be customized by replacing the `_.memoize.Cache`
8433 * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
8434 * method interface of `get`, `has`, and `set`.
8435 *
8436 * @static
8437 * @memberOf _
8438 * @category Function
8439 * @param {Function} func The function to have its output memoized.
8440 * @param {Function} [resolver] The function to resolve the cache key.
8441 * @returns {Function} Returns the new memoizing function.
8442 * @example
8443 *
8444 * var upperCase = _.memoize(function(string) {
8445 * return string.toUpperCase();
8446 * });
8447 *
8448 * upperCase('fred');
8449 * // => 'FRED'
8450 *
8451 * // modifying the result cache
8452 * upperCase.cache.set('fred', 'BARNEY');
8453 * upperCase('fred');
8454 * // => 'BARNEY'
8455 *
8456 * // replacing `_.memoize.Cache`
8457 * var object = { 'user': 'fred' };
8458 * var other = { 'user': 'barney' };
8459 * var identity = _.memoize(_.identity);
8460 *
8461 * identity(object);
8462 * // => { 'user': 'fred' }
8463 * identity(other);
8464 * // => { 'user': 'fred' }
8465 *
8466 * _.memoize.Cache = WeakMap;
8467 * var identity = _.memoize(_.identity);
8468 *
8469 * identity(object);
8470 * // => { 'user': 'fred' }
8471 * identity(other);
8472 * // => { 'user': 'barney' }
8473 */
8474 function memoize(func, resolver) {
8475 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
8476 throw new TypeError(FUNC_ERROR_TEXT);
8477 }
8478 var memoized = function() {
8479 var args = arguments,
8480 key = resolver ? resolver.apply(this, args) : args[0],
8481 cache = memoized.cache;
8482
8483 if (cache.has(key)) {
8484 return cache.get(key);
8485 }
8486 var result = func.apply(this, args);
8487 memoized.cache = cache.set(key, result);
8488 return result;
8489 };
8490 memoized.cache = new memoize.Cache;
8491 return memoized;
8492 }
8493
8494 /**
8495 * Creates a function that runs each argument through a corresponding
8496 * transform function.
8497 *
8498 * @static
8499 * @memberOf _
8500 * @category Function
8501 * @param {Function} func The function to wrap.
8502 * @param {...(Function|Function[])} [transforms] The functions to transform
8503 * arguments, specified as individual functions or arrays of functions.
8504 * @returns {Function} Returns the new function.
8505 * @example
8506 *
8507 * function doubled(n) {
8508 * return n * 2;
8509 * }
8510 *
8511 * function square(n) {
8512 * return n * n;
8513 * }
8514 *
8515 * var modded = _.modArgs(function(x, y) {
8516 * return [x, y];
8517 * }, square, doubled);
8518 *
8519 * modded(1, 2);
8520 * // => [1, 4]
8521 *
8522 * modded(5, 10);
8523 * // => [25, 20]
8524 */
8525 var modArgs = restParam(function(func, transforms) {
8526 transforms = baseFlatten(transforms);
8527 if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
8528 throw new TypeError(FUNC_ERROR_TEXT);
8529 }
8530 var length = transforms.length;
8531 return restParam(function(args) {
8532 var index = nativeMin(args.length, length);
8533 while (index--) {
8534 args[index] = transforms[index](args[index]);
8535 }
8536 return func.apply(this, args);
8537 });
8538 });
8539
8540 /**
8541 * Creates a function that negates the result of the predicate `func`. The
8542 * `func` predicate is invoked with the `this` binding and arguments of the
8543 * created function.
8544 *
8545 * @static
8546 * @memberOf _
8547 * @category Function
8548 * @param {Function} predicate The predicate to negate.
8549 * @returns {Function} Returns the new function.
8550 * @example
8551 *
8552 * function isEven(n) {
8553 * return n % 2 == 0;
8554 * }
8555 *
8556 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
8557 * // => [1, 3, 5]
8558 */
8559 function negate(predicate) {
8560 if (typeof predicate != 'function') {
8561 throw new TypeError(FUNC_ERROR_TEXT);
8562 }
8563 return function() {
8564 return !predicate.apply(this, arguments);
8565 };
8566 }
8567
8568 /**
8569 * Creates a function that is restricted to invoking `func` once. Repeat calls
8570 * to the function return the value of the first call. The `func` is invoked
8571 * with the `this` binding and arguments of the created function.
8572 *
8573 * @static
8574 * @memberOf _
8575 * @category Function
8576 * @param {Function} func The function to restrict.
8577 * @returns {Function} Returns the new restricted function.
8578 * @example
8579 *
8580 * var initialize = _.once(createApplication);
8581 * initialize();
8582 * initialize();
8583 * // `initialize` invokes `createApplication` once
8584 */
8585 function once(func) {
8586 return before(2, func);
8587 }
8588
8589 /**
8590 * Creates a function that invokes `func` with `partial` arguments prepended
8591 * to those provided to the new function. This method is like `_.bind` except
8592 * it does **not** alter the `this` binding.
8593 *
8594 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
8595 * builds, may be used as a placeholder for partially applied arguments.
8596 *
8597 * **Note:** This method does not set the "length" property of partially
8598 * applied functions.
8599 *
8600 * @static
8601 * @memberOf _
8602 * @category Function
8603 * @param {Function} func The function to partially apply arguments to.
8604 * @param {...*} [partials] The arguments to be partially applied.
8605 * @returns {Function} Returns the new partially applied function.
8606 * @example
8607 *
8608 * var greet = function(greeting, name) {
8609 * return greeting + ' ' + name;
8610 * };
8611 *
8612 * var sayHelloTo = _.partial(greet, 'hello');
8613 * sayHelloTo('fred');
8614 * // => 'hello fred'
8615 *
8616 * // using placeholders
8617 * var greetFred = _.partial(greet, _, 'fred');
8618 * greetFred('hi');
8619 * // => 'hi fred'
8620 */
8621 var partial = createPartial(PARTIAL_FLAG);
8622
8623 /**
8624 * This method is like `_.partial` except that partially applied arguments
8625 * are appended to those provided to the new function.
8626 *
8627 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
8628 * builds, may be used as a placeholder for partially applied arguments.
8629 *
8630 * **Note:** This method does not set the "length" property of partially
8631 * applied functions.
8632 *
8633 * @static
8634 * @memberOf _
8635 * @category Function
8636 * @param {Function} func The function to partially apply arguments to.
8637 * @param {...*} [partials] The arguments to be partially applied.
8638 * @returns {Function} Returns the new partially applied function.
8639 * @example
8640 *
8641 * var greet = function(greeting, name) {
8642 * return greeting + ' ' + name;
8643 * };
8644 *
8645 * var greetFred = _.partialRight(greet, 'fred');
8646 * greetFred('hi');
8647 * // => 'hi fred'
8648 *
8649 * // using placeholders
8650 * var sayHelloTo = _.partialRight(greet, 'hello', _);
8651 * sayHelloTo('fred');
8652 * // => 'hello fred'
8653 */
8654 var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
8655
8656 /**
8657 * Creates a function that invokes `func` with arguments arranged according
8658 * to the specified indexes where the argument value at the first index is
8659 * provided as the first argument, the argument value at the second index is
8660 * provided as the second argument, and so on.
8661 *
8662 * @static
8663 * @memberOf _
8664 * @category Function
8665 * @param {Function} func The function to rearrange arguments for.
8666 * @param {...(number|number[])} indexes The arranged argument indexes,
8667 * specified as individual indexes or arrays of indexes.
8668 * @returns {Function} Returns the new function.
8669 * @example
8670 *
8671 * var rearged = _.rearg(function(a, b, c) {
8672 * return [a, b, c];
8673 * }, 2, 0, 1);
8674 *
8675 * rearged('b', 'c', 'a')
8676 * // => ['a', 'b', 'c']
8677 *
8678 * var map = _.rearg(_.map, [1, 0]);
8679 * map(function(n) {
8680 * return n * 3;
8681 * }, [1, 2, 3]);
8682 * // => [3, 6, 9]
8683 */
8684 var rearg = restParam(function(func, indexes) {
8685 return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
8686 });
8687
8688 /**
8689 * Creates a function that invokes `func` with the `this` binding of the
8690 * created function and arguments from `start` and beyond provided as an array.
8691 *
8692 * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
8693 *
8694 * @static
8695 * @memberOf _
8696 * @category Function
8697 * @param {Function} func The function to apply a rest parameter to.
8698 * @param {number} [start=func.length-1] The start position of the rest parameter.
8699 * @returns {Function} Returns the new function.
8700 * @example
8701 *
8702 * var say = _.restParam(function(what, names) {
8703 * return what + ' ' + _.initial(names).join(', ') +
8704 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
8705 * });
8706 *
8707 * say('hello', 'fred', 'barney', 'pebbles');
8708 * // => 'hello fred, barney, & pebbles'
8709 */
8710 function restParam(func, start) {
8711 if (typeof func != 'function') {
8712 throw new TypeError(FUNC_ERROR_TEXT);
8713 }
8714 start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
8715 return function() {
8716 var args = arguments,
8717 index = -1,
8718 length = nativeMax(args.length - start, 0),
8719 rest = Array(length);
8720
8721 while (++index < length) {
8722 rest[index] = args[start + index];
8723 }
8724 switch (start) {
8725 case 0: return func.call(this, rest);
8726 case 1: return func.call(this, args[0], rest);
8727 case 2: return func.call(this, args[0], args[1], rest);
8728 }
8729 var otherArgs = Array(start + 1);
8730 index = -1;
8731 while (++index < start) {
8732 otherArgs[index] = args[index];
8733 }
8734 otherArgs[start] = rest;
8735 return func.apply(this, otherArgs);
8736 };
8737 }
8738
8739 /**
8740 * Creates a function that invokes `func` with the `this` binding of the created
8741 * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
8742 *
8743 * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
8744 *
8745 * @static
8746 * @memberOf _
8747 * @category Function
8748 * @param {Function} func The function to spread arguments over.
8749 * @returns {Function} Returns the new function.
8750 * @example
8751 *
8752 * var say = _.spread(function(who, what) {
8753 * return who + ' says ' + what;
8754 * });
8755 *
8756 * say(['fred', 'hello']);
8757 * // => 'fred says hello'
8758 *
8759 * // with a Promise
8760 * var numbers = Promise.all([
8761 * Promise.resolve(40),
8762 * Promise.resolve(36)
8763 * ]);
8764 *
8765 * numbers.then(_.spread(function(x, y) {
8766 * return x + y;
8767 * }));
8768 * // => a Promise of 76
8769 */
8770 function spread(func) {
8771 if (typeof func != 'function') {
8772 throw new TypeError(FUNC_ERROR_TEXT);
8773 }
8774 return function(array) {
8775 return func.apply(this, array);
8776 };
8777 }
8778
8779 /**
8780 * Creates a throttled function that only invokes `func` at most once per
8781 * every `wait` milliseconds. The throttled function comes with a `cancel`
8782 * method to cancel delayed invocations. Provide an options object to indicate
8783 * that `func` should be invoked on the leading and/or trailing edge of the
8784 * `wait` timeout. Subsequent calls to the throttled function return the
8785 * result of the last `func` call.
8786 *
8787 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
8788 * on the trailing edge of the timeout only if the the throttled function is
8789 * invoked more than once during the `wait` timeout.
8790 *
8791 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
8792 * for details over the differences between `_.throttle` and `_.debounce`.
8793 *
8794 * @static
8795 * @memberOf _
8796 * @category Function
8797 * @param {Function} func The function to throttle.
8798 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
8799 * @param {Object} [options] The options object.
8800 * @param {boolean} [options.leading=true] Specify invoking on the leading
8801 * edge of the timeout.
8802 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
8803 * edge of the timeout.
8804 * @returns {Function} Returns the new throttled function.
8805 * @example
8806 *
8807 * // avoid excessively updating the position while scrolling
8808 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
8809 *
8810 * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
8811 * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
8812 * 'trailing': false
8813 * }));
8814 *
8815 * // cancel a trailing throttled call
8816 * jQuery(window).on('popstate', throttled.cancel);
8817 */
8818 function throttle(func, wait, options) {
8819 var leading = true,
8820 trailing = true;
8821
8822 if (typeof func != 'function') {
8823 throw new TypeError(FUNC_ERROR_TEXT);
8824 }
8825 if (options === false) {
8826 leading = false;
8827 } else if (isObject(options)) {
8828 leading = 'leading' in options ? !!options.leading : leading;
8829 trailing = 'trailing' in options ? !!options.trailing : trailing;
8830 }
8831 return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
8832 }
8833
8834 /**
8835 * Creates a function that provides `value` to the wrapper function as its
8836 * first argument. Any additional arguments provided to the function are
8837 * appended to those provided to the wrapper function. The wrapper is invoked
8838 * with the `this` binding of the created function.
8839 *
8840 * @static
8841 * @memberOf _
8842 * @category Function
8843 * @param {*} value The value to wrap.
8844 * @param {Function} wrapper The wrapper function.
8845 * @returns {Function} Returns the new function.
8846 * @example
8847 *
8848 * var p = _.wrap(_.escape, function(func, text) {
8849 * return '<p>' + func(text) + '</p>';
8850 * });
8851 *
8852 * p('fred, barney, & pebbles');
8853 * // => '<p>fred, barney, &amp; pebbles</p>'
8854 */
8855 function wrap(value, wrapper) {
8856 wrapper = wrapper == null ? identity : wrapper;
8857 return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
8858 }
8859
8860 /*------------------------------------------------------------------------*/
8861
8862 /**
8863 * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
8864 * otherwise they are assigned by reference. If `customizer` is provided it is
8865 * invoked to produce the cloned values. If `customizer` returns `undefined`
8866 * cloning is handled by the method instead. The `customizer` is bound to
8867 * `thisArg` and invoked with two argument; (value [, index|key, object]).
8868 *
8869 * **Note:** This method is loosely based on the
8870 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
8871 * The enumerable properties of `arguments` objects and objects created by
8872 * constructors other than `Object` are cloned to plain `Object` objects. An
8873 * empty object is returned for uncloneable values such as functions, DOM nodes,
8874 * Maps, Sets, and WeakMaps.
8875 *
8876 * @static
8877 * @memberOf _
8878 * @category Lang
8879 * @param {*} value The value to clone.
8880 * @param {boolean} [isDeep] Specify a deep clone.
8881 * @param {Function} [customizer] The function to customize cloning values.
8882 * @param {*} [thisArg] The `this` binding of `customizer`.
8883 * @returns {*} Returns the cloned value.
8884 * @example
8885 *
8886 * var users = [
8887 * { 'user': 'barney' },
8888 * { 'user': 'fred' }
8889 * ];
8890 *
8891 * var shallow = _.clone(users);
8892 * shallow[0] === users[0];
8893 * // => true
8894 *
8895 * var deep = _.clone(users, true);
8896 * deep[0] === users[0];
8897 * // => false
8898 *
8899 * // using a customizer callback
8900 * var el = _.clone(document.body, function(value) {
8901 * if (_.isElement(value)) {
8902 * return value.cloneNode(false);
8903 * }
8904 * });
8905 *
8906 * el === document.body
8907 * // => false
8908 * el.nodeName
8909 * // => BODY
8910 * el.childNodes.length;
8911 * // => 0
8912 */
8913 function clone(value, isDeep, customizer, thisArg) {
8914 if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
8915 isDeep = false;
8916 }
8917 else if (typeof isDeep == 'function') {
8918 thisArg = customizer;
8919 customizer = isDeep;
8920 isDeep = false;
8921 }
8922 return typeof customizer == 'function'
8923 ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1))
8924 : baseClone(value, isDeep);
8925 }
8926
8927 /**
8928 * Creates a deep clone of `value`. If `customizer` is provided it is invoked
8929 * to produce the cloned values. If `customizer` returns `undefined` cloning
8930 * is handled by the method instead. The `customizer` is bound to `thisArg`
8931 * and invoked with two argument; (value [, index|key, object]).
8932 *
8933 * **Note:** This method is loosely based on the
8934 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
8935 * The enumerable properties of `arguments` objects and objects created by
8936 * constructors other than `Object` are cloned to plain `Object` objects. An
8937 * empty object is returned for uncloneable values such as functions, DOM nodes,
8938 * Maps, Sets, and WeakMaps.
8939 *
8940 * @static
8941 * @memberOf _
8942 * @category Lang
8943 * @param {*} value The value to deep clone.
8944 * @param {Function} [customizer] The function to customize cloning values.
8945 * @param {*} [thisArg] The `this` binding of `customizer`.
8946 * @returns {*} Returns the deep cloned value.
8947 * @example
8948 *
8949 * var users = [
8950 * { 'user': 'barney' },
8951 * { 'user': 'fred' }
8952 * ];
8953 *
8954 * var deep = _.cloneDeep(users);
8955 * deep[0] === users[0];
8956 * // => false
8957 *
8958 * // using a customizer callback
8959 * var el = _.cloneDeep(document.body, function(value) {
8960 * if (_.isElement(value)) {
8961 * return value.cloneNode(true);
8962 * }
8963 * });
8964 *
8965 * el === document.body
8966 * // => false
8967 * el.nodeName
8968 * // => BODY
8969 * el.childNodes.length;
8970 * // => 20
8971 */
8972 function cloneDeep(value, customizer, thisArg) {
8973 return typeof customizer == 'function'
8974 ? baseClone(value, true, bindCallback(customizer, thisArg, 1))
8975 : baseClone(value, true);
8976 }
8977
8978 /**
8979 * Checks if `value` is greater than `other`.
8980 *
8981 * @static
8982 * @memberOf _
8983 * @category Lang
8984 * @param {*} value The value to compare.
8985 * @param {*} other The other value to compare.
8986 * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
8987 * @example
8988 *
8989 * _.gt(3, 1);
8990 * // => true
8991 *
8992 * _.gt(3, 3);
8993 * // => false
8994 *
8995 * _.gt(1, 3);
8996 * // => false
8997 */
8998 function gt(value, other) {
8999 return value > other;
9000 }
9001
9002 /**
9003 * Checks if `value` is greater than or equal to `other`.
9004 *
9005 * @static
9006 * @memberOf _
9007 * @category Lang
9008 * @param {*} value The value to compare.
9009 * @param {*} other The other value to compare.
9010 * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
9011 * @example
9012 *
9013 * _.gte(3, 1);
9014 * // => true
9015 *
9016 * _.gte(3, 3);
9017 * // => true
9018 *
9019 * _.gte(1, 3);
9020 * // => false
9021 */
9022 function gte(value, other) {
9023 return value >= other;
9024 }
9025
9026 /**
9027 * Checks if `value` is classified as an `arguments` object.
9028 *
9029 * @static
9030 * @memberOf _
9031 * @category Lang
9032 * @param {*} value The value to check.
9033 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9034 * @example
9035 *
9036 * _.isArguments(function() { return arguments; }());
9037 * // => true
9038 *
9039 * _.isArguments([1, 2, 3]);
9040 * // => false
9041 */
9042 function isArguments(value) {
9043 return isObjectLike(value) && isArrayLike(value) &&
9044 hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
9045 }
9046
9047 /**
9048 * Checks if `value` is classified as an `Array` object.
9049 *
9050 * @static
9051 * @memberOf _
9052 * @category Lang
9053 * @param {*} value The value to check.
9054 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9055 * @example
9056 *
9057 * _.isArray([1, 2, 3]);
9058 * // => true
9059 *
9060 * _.isArray(function() { return arguments; }());
9061 * // => false
9062 */
9063 var isArray = nativeIsArray || function(value) {
9064 return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
9065 };
9066
9067 /**
9068 * Checks if `value` is classified as a boolean primitive or object.
9069 *
9070 * @static
9071 * @memberOf _
9072 * @category Lang
9073 * @param {*} value The value to check.
9074 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9075 * @example
9076 *
9077 * _.isBoolean(false);
9078 * // => true
9079 *
9080 * _.isBoolean(null);
9081 * // => false
9082 */
9083 function isBoolean(value) {
9084 return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
9085 }
9086
9087 /**
9088 * Checks if `value` is classified as a `Date` object.
9089 *
9090 * @static
9091 * @memberOf _
9092 * @category Lang
9093 * @param {*} value The value to check.
9094 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9095 * @example
9096 *
9097 * _.isDate(new Date);
9098 * // => true
9099 *
9100 * _.isDate('Mon April 23 2012');
9101 * // => false
9102 */
9103 function isDate(value) {
9104 return isObjectLike(value) && objToString.call(value) == dateTag;
9105 }
9106
9107 /**
9108 * Checks if `value` is a DOM element.
9109 *
9110 * @static
9111 * @memberOf _
9112 * @category Lang
9113 * @param {*} value The value to check.
9114 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
9115 * @example
9116 *
9117 * _.isElement(document.body);
9118 * // => true
9119 *
9120 * _.isElement('<body>');
9121 * // => false
9122 */
9123 function isElement(value) {
9124 return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
9125 }
9126
9127 /**
9128 * Checks if `value` is empty. A value is considered empty unless it is an
9129 * `arguments` object, array, string, or jQuery-like collection with a length
9130 * greater than `0` or an object with own enumerable properties.
9131 *
9132 * @static
9133 * @memberOf _
9134 * @category Lang
9135 * @param {Array|Object|string} value The value to inspect.
9136 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
9137 * @example
9138 *
9139 * _.isEmpty(null);
9140 * // => true
9141 *
9142 * _.isEmpty(true);
9143 * // => true
9144 *
9145 * _.isEmpty(1);
9146 * // => true
9147 *
9148 * _.isEmpty([1, 2, 3]);
9149 * // => false
9150 *
9151 * _.isEmpty({ 'a': 1 });
9152 * // => false
9153 */
9154 function isEmpty(value) {
9155 if (value == null) {
9156 return true;
9157 }
9158 if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
9159 (isObjectLike(value) && isFunction(value.splice)))) {
9160 return !value.length;
9161 }
9162 return !keys(value).length;
9163 }
9164
9165 /**
9166 * Performs a deep comparison between two values to determine if they are
9167 * equivalent. If `customizer` is provided it is invoked to compare values.
9168 * If `customizer` returns `undefined` comparisons are handled by the method
9169 * instead. The `customizer` is bound to `thisArg` and invoked with three
9170 * arguments: (value, other [, index|key]).
9171 *
9172 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
9173 * numbers, `Object` objects, regexes, and strings. Objects are compared by
9174 * their own, not inherited, enumerable properties. Functions and DOM nodes
9175 * are **not** supported. Provide a customizer function to extend support
9176 * for comparing other values.
9177 *
9178 * @static
9179 * @memberOf _
9180 * @alias eq
9181 * @category Lang
9182 * @param {*} value The value to compare.
9183 * @param {*} other The other value to compare.
9184 * @param {Function} [customizer] The function to customize value comparisons.
9185 * @param {*} [thisArg] The `this` binding of `customizer`.
9186 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
9187 * @example
9188 *
9189 * var object = { 'user': 'fred' };
9190 * var other = { 'user': 'fred' };
9191 *
9192 * object == other;
9193 * // => false
9194 *
9195 * _.isEqual(object, other);
9196 * // => true
9197 *
9198 * // using a customizer callback
9199 * var array = ['hello', 'goodbye'];
9200 * var other = ['hi', 'goodbye'];
9201 *
9202 * _.isEqual(array, other, function(value, other) {
9203 * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
9204 * return true;
9205 * }
9206 * });
9207 * // => true
9208 */
9209 function isEqual(value, other, customizer, thisArg) {
9210 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
9211 var result = customizer ? customizer(value, other) : undefined;
9212 return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
9213 }
9214
9215 /**
9216 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
9217 * `SyntaxError`, `TypeError`, or `URIError` object.
9218 *
9219 * @static
9220 * @memberOf _
9221 * @category Lang
9222 * @param {*} value The value to check.
9223 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
9224 * @example
9225 *
9226 * _.isError(new Error);
9227 * // => true
9228 *
9229 * _.isError(Error);
9230 * // => false
9231 */
9232 function isError(value) {
9233 return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
9234 }
9235
9236 /**
9237 * Checks if `value` is a finite primitive number.
9238 *
9239 * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite).
9240 *
9241 * @static
9242 * @memberOf _
9243 * @category Lang
9244 * @param {*} value The value to check.
9245 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
9246 * @example
9247 *
9248 * _.isFinite(10);
9249 * // => true
9250 *
9251 * _.isFinite('10');
9252 * // => false
9253 *
9254 * _.isFinite(true);
9255 * // => false
9256 *
9257 * _.isFinite(Object(10));
9258 * // => false
9259 *
9260 * _.isFinite(Infinity);
9261 * // => false
9262 */
9263 function isFinite(value) {
9264 return typeof value == 'number' && nativeIsFinite(value);
9265 }
9266
9267 /**
9268 * Checks if `value` is classified as a `Function` object.
9269 *
9270 * @static
9271 * @memberOf _
9272 * @category Lang
9273 * @param {*} value The value to check.
9274 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9275 * @example
9276 *
9277 * _.isFunction(_);
9278 * // => true
9279 *
9280 * _.isFunction(/abc/);
9281 * // => false
9282 */
9283 function isFunction(value) {
9284 // The use of `Object#toString` avoids issues with the `typeof` operator
9285 // in older versions of Chrome and Safari which return 'function' for regexes
9286 // and Safari 8 equivalents which return 'object' for typed array constructors.
9287 return isObject(value) && objToString.call(value) == funcTag;
9288 }
9289
9290 /**
9291 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
9292 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
9293 *
9294 * @static
9295 * @memberOf _
9296 * @category Lang
9297 * @param {*} value The value to check.
9298 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
9299 * @example
9300 *
9301 * _.isObject({});
9302 * // => true
9303 *
9304 * _.isObject([1, 2, 3]);
9305 * // => true
9306 *
9307 * _.isObject(1);
9308 * // => false
9309 */
9310 function isObject(value) {
9311 // Avoid a V8 JIT bug in Chrome 19-20.
9312 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
9313 var type = typeof value;
9314 return !!value && (type == 'object' || type == 'function');
9315 }
9316
9317 /**
9318 * Performs a deep comparison between `object` and `source` to determine if
9319 * `object` contains equivalent property values. If `customizer` is provided
9320 * it is invoked to compare values. If `customizer` returns `undefined`
9321 * comparisons are handled by the method instead. The `customizer` is bound
9322 * to `thisArg` and invoked with three arguments: (value, other, index|key).
9323 *
9324 * **Note:** This method supports comparing properties of arrays, booleans,
9325 * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
9326 * and DOM nodes are **not** supported. Provide a customizer function to extend
9327 * support for comparing other values.
9328 *
9329 * @static
9330 * @memberOf _
9331 * @category Lang
9332 * @param {Object} object The object to inspect.
9333 * @param {Object} source The object of property values to match.
9334 * @param {Function} [customizer] The function to customize value comparisons.
9335 * @param {*} [thisArg] The `this` binding of `customizer`.
9336 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
9337 * @example
9338 *
9339 * var object = { 'user': 'fred', 'age': 40 };
9340 *
9341 * _.isMatch(object, { 'age': 40 });
9342 * // => true
9343 *
9344 * _.isMatch(object, { 'age': 36 });
9345 * // => false
9346 *
9347 * // using a customizer callback
9348 * var object = { 'greeting': 'hello' };
9349 * var source = { 'greeting': 'hi' };
9350 *
9351 * _.isMatch(object, source, function(value, other) {
9352 * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
9353 * });
9354 * // => true
9355 */
9356 function isMatch(object, source, customizer, thisArg) {
9357 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
9358 return baseIsMatch(object, getMatchData(source), customizer);
9359 }
9360
9361 /**
9362 * Checks if `value` is `NaN`.
9363 *
9364 * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
9365 * which returns `true` for `undefined` and other non-numeric values.
9366 *
9367 * @static
9368 * @memberOf _
9369 * @category Lang
9370 * @param {*} value The value to check.
9371 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
9372 * @example
9373 *
9374 * _.isNaN(NaN);
9375 * // => true
9376 *
9377 * _.isNaN(new Number(NaN));
9378 * // => true
9379 *
9380 * isNaN(undefined);
9381 * // => true
9382 *
9383 * _.isNaN(undefined);
9384 * // => false
9385 */
9386 function isNaN(value) {
9387 // An `NaN` primitive is the only value that is not equal to itself.
9388 // Perform the `toStringTag` check first to avoid errors with some host objects in IE.
9389 return isNumber(value) && value != +value;
9390 }
9391
9392 /**
9393 * Checks if `value` is a native function.
9394 *
9395 * @static
9396 * @memberOf _
9397 * @category Lang
9398 * @param {*} value The value to check.
9399 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
9400 * @example
9401 *
9402 * _.isNative(Array.prototype.push);
9403 * // => true
9404 *
9405 * _.isNative(_);
9406 * // => false
9407 */
9408 function isNative(value) {
9409 if (value == null) {
9410 return false;
9411 }
9412 if (isFunction(value)) {
9413 return reIsNative.test(fnToString.call(value));
9414 }
9415 return isObjectLike(value) && reIsHostCtor.test(value);
9416 }
9417
9418 /**
9419 * Checks if `value` is `null`.
9420 *
9421 * @static
9422 * @memberOf _
9423 * @category Lang
9424 * @param {*} value The value to check.
9425 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
9426 * @example
9427 *
9428 * _.isNull(null);
9429 * // => true
9430 *
9431 * _.isNull(void 0);
9432 * // => false
9433 */
9434 function isNull(value) {
9435 return value === null;
9436 }
9437
9438 /**
9439 * Checks if `value` is classified as a `Number` primitive or object.
9440 *
9441 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
9442 * as numbers, use the `_.isFinite` method.
9443 *
9444 * @static
9445 * @memberOf _
9446 * @category Lang
9447 * @param {*} value The value to check.
9448 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9449 * @example
9450 *
9451 * _.isNumber(8.4);
9452 * // => true
9453 *
9454 * _.isNumber(NaN);
9455 * // => true
9456 *
9457 * _.isNumber('8.4');
9458 * // => false
9459 */
9460 function isNumber(value) {
9461 return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
9462 }
9463
9464 /**
9465 * Checks if `value` is a plain object, that is, an object created by the
9466 * `Object` constructor or one with a `[[Prototype]]` of `null`.
9467 *
9468 * **Note:** This method assumes objects created by the `Object` constructor
9469 * have no inherited enumerable properties.
9470 *
9471 * @static
9472 * @memberOf _
9473 * @category Lang
9474 * @param {*} value The value to check.
9475 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
9476 * @example
9477 *
9478 * function Foo() {
9479 * this.a = 1;
9480 * }
9481 *
9482 * _.isPlainObject(new Foo);
9483 * // => false
9484 *
9485 * _.isPlainObject([1, 2, 3]);
9486 * // => false
9487 *
9488 * _.isPlainObject({ 'x': 0, 'y': 0 });
9489 * // => true
9490 *
9491 * _.isPlainObject(Object.create(null));
9492 * // => true
9493 */
9494 function isPlainObject(value) {
9495 var Ctor;
9496
9497 // Exit early for non `Object` objects.
9498 if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
9499 (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
9500 return false;
9501 }
9502 // IE < 9 iterates inherited properties before own properties. If the first
9503 // iterated property is an object's own property then there are no inherited
9504 // enumerable properties.
9505 var result;
9506 // In most environments an object's own properties are iterated before
9507 // its inherited properties. If the last iterated property is an object's
9508 // own property then there are no inherited enumerable properties.
9509 baseForIn(value, function(subValue, key) {
9510 result = key;
9511 });
9512 return result === undefined || hasOwnProperty.call(value, result);
9513 }
9514
9515 /**
9516 * Checks if `value` is classified as a `RegExp` object.
9517 *
9518 * @static
9519 * @memberOf _
9520 * @category Lang
9521 * @param {*} value The value to check.
9522 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9523 * @example
9524 *
9525 * _.isRegExp(/abc/);
9526 * // => true
9527 *
9528 * _.isRegExp('/abc/');
9529 * // => false
9530 */
9531 function isRegExp(value) {
9532 return isObject(value) && objToString.call(value) == regexpTag;
9533 }
9534
9535 /**
9536 * Checks if `value` is classified as a `String` primitive or object.
9537 *
9538 * @static
9539 * @memberOf _
9540 * @category Lang
9541 * @param {*} value The value to check.
9542 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9543 * @example
9544 *
9545 * _.isString('abc');
9546 * // => true
9547 *
9548 * _.isString(1);
9549 * // => false
9550 */
9551 function isString(value) {
9552 return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
9553 }
9554
9555 /**
9556 * Checks if `value` is classified as a typed array.
9557 *
9558 * @static
9559 * @memberOf _
9560 * @category Lang
9561 * @param {*} value The value to check.
9562 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
9563 * @example
9564 *
9565 * _.isTypedArray(new Uint8Array);
9566 * // => true
9567 *
9568 * _.isTypedArray([]);
9569 * // => false
9570 */
9571 function isTypedArray(value) {
9572 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
9573 }
9574
9575 /**
9576 * Checks if `value` is `undefined`.
9577 *
9578 * @static
9579 * @memberOf _
9580 * @category Lang
9581 * @param {*} value The value to check.
9582 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
9583 * @example
9584 *
9585 * _.isUndefined(void 0);
9586 * // => true
9587 *
9588 * _.isUndefined(null);
9589 * // => false
9590 */
9591 function isUndefined(value) {
9592 return value === undefined;
9593 }
9594
9595 /**
9596 * Checks if `value` is less than `other`.
9597 *
9598 * @static
9599 * @memberOf _
9600 * @category Lang
9601 * @param {*} value The value to compare.
9602 * @param {*} other The other value to compare.
9603 * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
9604 * @example
9605 *
9606 * _.lt(1, 3);
9607 * // => true
9608 *
9609 * _.lt(3, 3);
9610 * // => false
9611 *
9612 * _.lt(3, 1);
9613 * // => false
9614 */
9615 function lt(value, other) {
9616 return value < other;
9617 }
9618
9619 /**
9620 * Checks if `value` is less than or equal to `other`.
9621 *
9622 * @static
9623 * @memberOf _
9624 * @category Lang
9625 * @param {*} value The value to compare.
9626 * @param {*} other The other value to compare.
9627 * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
9628 * @example
9629 *
9630 * _.lte(1, 3);
9631 * // => true
9632 *
9633 * _.lte(3, 3);
9634 * // => true
9635 *
9636 * _.lte(3, 1);
9637 * // => false
9638 */
9639 function lte(value, other) {
9640 return value <= other;
9641 }
9642
9643 /**
9644 * Converts `value` to an array.
9645 *
9646 * @static
9647 * @memberOf _
9648 * @category Lang
9649 * @param {*} value The value to convert.
9650 * @returns {Array} Returns the converted array.
9651 * @example
9652 *
9653 * (function() {
9654 * return _.toArray(arguments).slice(1);
9655 * }(1, 2, 3));
9656 * // => [2, 3]
9657 */
9658 function toArray(value) {
9659 var length = value ? getLength(value) : 0;
9660 if (!isLength(length)) {
9661 return values(value);
9662 }
9663 if (!length) {
9664 return [];
9665 }
9666 return arrayCopy(value);
9667 }
9668
9669 /**
9670 * Converts `value` to a plain object flattening inherited enumerable
9671 * properties of `value` to own properties of the plain object.
9672 *
9673 * @static
9674 * @memberOf _
9675 * @category Lang
9676 * @param {*} value The value to convert.
9677 * @returns {Object} Returns the converted plain object.
9678 * @example
9679 *
9680 * function Foo() {
9681 * this.b = 2;
9682 * }
9683 *
9684 * Foo.prototype.c = 3;
9685 *
9686 * _.assign({ 'a': 1 }, new Foo);
9687 * // => { 'a': 1, 'b': 2 }
9688 *
9689 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
9690 * // => { 'a': 1, 'b': 2, 'c': 3 }
9691 */
9692 function toPlainObject(value) {
9693 return baseCopy(value, keysIn(value));
9694 }
9695
9696 /*------------------------------------------------------------------------*/
9697
9698 /**
9699 * Recursively merges own enumerable properties of the source object(s), that
9700 * don't resolve to `undefined` into the destination object. Subsequent sources
9701 * overwrite property assignments of previous sources. If `customizer` is
9702 * provided it is invoked to produce the merged values of the destination and
9703 * source properties. If `customizer` returns `undefined` merging is handled
9704 * by the method instead. The `customizer` is bound to `thisArg` and invoked
9705 * with five arguments: (objectValue, sourceValue, key, object, source).
9706 *
9707 * @static
9708 * @memberOf _
9709 * @category Object
9710 * @param {Object} object The destination object.
9711 * @param {...Object} [sources] The source objects.
9712 * @param {Function} [customizer] The function to customize assigned values.
9713 * @param {*} [thisArg] The `this` binding of `customizer`.
9714 * @returns {Object} Returns `object`.
9715 * @example
9716 *
9717 * var users = {
9718 * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
9719 * };
9720 *
9721 * var ages = {
9722 * 'data': [{ 'age': 36 }, { 'age': 40 }]
9723 * };
9724 *
9725 * _.merge(users, ages);
9726 * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
9727 *
9728 * // using a customizer callback
9729 * var object = {
9730 * 'fruits': ['apple'],
9731 * 'vegetables': ['beet']
9732 * };
9733 *
9734 * var other = {
9735 * 'fruits': ['banana'],
9736 * 'vegetables': ['carrot']
9737 * };
9738 *
9739 * _.merge(object, other, function(a, b) {
9740 * if (_.isArray(a)) {
9741 * return a.concat(b);
9742 * }
9743 * });
9744 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
9745 */
9746 var merge = createAssigner(baseMerge);
9747
9748 /**
9749 * Assigns own enumerable properties of source object(s) to the destination
9750 * object. Subsequent sources overwrite property assignments of previous sources.
9751 * If `customizer` is provided it is invoked to produce the assigned values.
9752 * The `customizer` is bound to `thisArg` and invoked with five arguments:
9753 * (objectValue, sourceValue, key, object, source).
9754 *
9755 * **Note:** This method mutates `object` and is based on
9756 * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
9757 *
9758 * @static
9759 * @memberOf _
9760 * @alias extend
9761 * @category Object
9762 * @param {Object} object The destination object.
9763 * @param {...Object} [sources] The source objects.
9764 * @param {Function} [customizer] The function to customize assigned values.
9765 * @param {*} [thisArg] The `this` binding of `customizer`.
9766 * @returns {Object} Returns `object`.
9767 * @example
9768 *
9769 * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
9770 * // => { 'user': 'fred', 'age': 40 }
9771 *
9772 * // using a customizer callback
9773 * var defaults = _.partialRight(_.assign, function(value, other) {
9774 * return _.isUndefined(value) ? other : value;
9775 * });
9776 *
9777 * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
9778 * // => { 'user': 'barney', 'age': 36 }
9779 */
9780 var assign = createAssigner(function(object, source, customizer) {
9781 return customizer
9782 ? assignWith(object, source, customizer)
9783 : baseAssign(object, source);
9784 });
9785
9786 /**
9787 * Creates an object that inherits from the given `prototype` object. If a
9788 * `properties` object is provided its own enumerable properties are assigned
9789 * to the created object.
9790 *
9791 * @static
9792 * @memberOf _
9793 * @category Object
9794 * @param {Object} prototype The object to inherit from.
9795 * @param {Object} [properties] The properties to assign to the object.
9796 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
9797 * @returns {Object} Returns the new object.
9798 * @example
9799 *
9800 * function Shape() {
9801 * this.x = 0;
9802 * this.y = 0;
9803 * }
9804 *
9805 * function Circle() {
9806 * Shape.call(this);
9807 * }
9808 *
9809 * Circle.prototype = _.create(Shape.prototype, {
9810 * 'constructor': Circle
9811 * });
9812 *
9813 * var circle = new Circle;
9814 * circle instanceof Circle;
9815 * // => true
9816 *
9817 * circle instanceof Shape;
9818 * // => true
9819 */
9820 function create(prototype, properties, guard) {
9821 var result = baseCreate(prototype);
9822 if (guard && isIterateeCall(prototype, properties, guard)) {
9823 properties = undefined;
9824 }
9825 return properties ? baseAssign(result, properties) : result;
9826 }
9827
9828 /**
9829 * Assigns own enumerable properties of source object(s) to the destination
9830 * object for all destination properties that resolve to `undefined`. Once a
9831 * property is set, additional values of the same property are ignored.
9832 *
9833 * **Note:** This method mutates `object`.
9834 *
9835 * @static
9836 * @memberOf _
9837 * @category Object
9838 * @param {Object} object The destination object.
9839 * @param {...Object} [sources] The source objects.
9840 * @returns {Object} Returns `object`.
9841 * @example
9842 *
9843 * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
9844 * // => { 'user': 'barney', 'age': 36 }
9845 */
9846 var defaults = createDefaults(assign, assignDefaults);
9847
9848 /**
9849 * This method is like `_.defaults` except that it recursively assigns
9850 * default properties.
9851 *
9852 * **Note:** This method mutates `object`.
9853 *
9854 * @static
9855 * @memberOf _
9856 * @category Object
9857 * @param {Object} object The destination object.
9858 * @param {...Object} [sources] The source objects.
9859 * @returns {Object} Returns `object`.
9860 * @example
9861 *
9862 * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
9863 * // => { 'user': { 'name': 'barney', 'age': 36 } }
9864 *
9865 */
9866 var defaultsDeep = createDefaults(merge, mergeDefaults);
9867
9868 /**
9869 * This method is like `_.find` except that it returns the key of the first
9870 * element `predicate` returns truthy for instead of the element itself.
9871 *
9872 * If a property name is provided for `predicate` the created `_.property`
9873 * style callback returns the property value of the given element.
9874 *
9875 * If a value is also provided for `thisArg` the created `_.matchesProperty`
9876 * style callback returns `true` for elements that have a matching property
9877 * value, else `false`.
9878 *
9879 * If an object is provided for `predicate` the created `_.matches` style
9880 * callback returns `true` for elements that have the properties of the given
9881 * object, else `false`.
9882 *
9883 * @static
9884 * @memberOf _
9885 * @category Object
9886 * @param {Object} object The object to search.
9887 * @param {Function|Object|string} [predicate=_.identity] The function invoked
9888 * per iteration.
9889 * @param {*} [thisArg] The `this` binding of `predicate`.
9890 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
9891 * @example
9892 *
9893 * var users = {
9894 * 'barney': { 'age': 36, 'active': true },
9895 * 'fred': { 'age': 40, 'active': false },
9896 * 'pebbles': { 'age': 1, 'active': true }
9897 * };
9898 *
9899 * _.findKey(users, function(chr) {
9900 * return chr.age < 40;
9901 * });
9902 * // => 'barney' (iteration order is not guaranteed)
9903 *
9904 * // using the `_.matches` callback shorthand
9905 * _.findKey(users, { 'age': 1, 'active': true });
9906 * // => 'pebbles'
9907 *
9908 * // using the `_.matchesProperty` callback shorthand
9909 * _.findKey(users, 'active', false);
9910 * // => 'fred'
9911 *
9912 * // using the `_.property` callback shorthand
9913 * _.findKey(users, 'active');
9914 * // => 'barney'
9915 */
9916 var findKey = createFindKey(baseForOwn);
9917
9918 /**
9919 * This method is like `_.findKey` except that it iterates over elements of
9920 * a collection in the opposite order.
9921 *
9922 * If a property name is provided for `predicate` the created `_.property`
9923 * style callback returns the property value of the given element.
9924 *
9925 * If a value is also provided for `thisArg` the created `_.matchesProperty`
9926 * style callback returns `true` for elements that have a matching property
9927 * value, else `false`.
9928 *
9929 * If an object is provided for `predicate` the created `_.matches` style
9930 * callback returns `true` for elements that have the properties of the given
9931 * object, else `false`.
9932 *
9933 * @static
9934 * @memberOf _
9935 * @category Object
9936 * @param {Object} object The object to search.
9937 * @param {Function|Object|string} [predicate=_.identity] The function invoked
9938 * per iteration.
9939 * @param {*} [thisArg] The `this` binding of `predicate`.
9940 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
9941 * @example
9942 *
9943 * var users = {
9944 * 'barney': { 'age': 36, 'active': true },
9945 * 'fred': { 'age': 40, 'active': false },
9946 * 'pebbles': { 'age': 1, 'active': true }
9947 * };
9948 *
9949 * _.findLastKey(users, function(chr) {
9950 * return chr.age < 40;
9951 * });
9952 * // => returns `pebbles` assuming `_.findKey` returns `barney`
9953 *
9954 * // using the `_.matches` callback shorthand
9955 * _.findLastKey(users, { 'age': 36, 'active': true });
9956 * // => 'barney'
9957 *
9958 * // using the `_.matchesProperty` callback shorthand
9959 * _.findLastKey(users, 'active', false);
9960 * // => 'fred'
9961 *
9962 * // using the `_.property` callback shorthand
9963 * _.findLastKey(users, 'active');
9964 * // => 'pebbles'
9965 */
9966 var findLastKey = createFindKey(baseForOwnRight);
9967
9968 /**
9969 * Iterates over own and inherited enumerable properties of an object invoking
9970 * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
9971 * with three arguments: (value, key, object). Iteratee functions may exit
9972 * iteration early by explicitly returning `false`.
9973 *
9974 * @static
9975 * @memberOf _
9976 * @category Object
9977 * @param {Object} object The object to iterate over.
9978 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
9979 * @param {*} [thisArg] The `this` binding of `iteratee`.
9980 * @returns {Object} Returns `object`.
9981 * @example
9982 *
9983 * function Foo() {
9984 * this.a = 1;
9985 * this.b = 2;
9986 * }
9987 *
9988 * Foo.prototype.c = 3;
9989 *
9990 * _.forIn(new Foo, function(value, key) {
9991 * console.log(key);
9992 * });
9993 * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
9994 */
9995 var forIn = createForIn(baseFor);
9996
9997 /**
9998 * This method is like `_.forIn` except that it iterates over properties of
9999 * `object` in the opposite order.
10000 *
10001 * @static
10002 * @memberOf _
10003 * @category Object
10004 * @param {Object} object The object to iterate over.
10005 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
10006 * @param {*} [thisArg] The `this` binding of `iteratee`.
10007 * @returns {Object} Returns `object`.
10008 * @example
10009 *
10010 * function Foo() {
10011 * this.a = 1;
10012 * this.b = 2;
10013 * }
10014 *
10015 * Foo.prototype.c = 3;
10016 *
10017 * _.forInRight(new Foo, function(value, key) {
10018 * console.log(key);
10019 * });
10020 * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
10021 */
10022 var forInRight = createForIn(baseForRight);
10023
10024 /**
10025 * Iterates over own enumerable properties of an object invoking `iteratee`
10026 * for each property. The `iteratee` is bound to `thisArg` and invoked with
10027 * three arguments: (value, key, object). Iteratee functions may exit iteration
10028 * early by explicitly returning `false`.
10029 *
10030 * @static
10031 * @memberOf _
10032 * @category Object
10033 * @param {Object} object The object to iterate over.
10034 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
10035 * @param {*} [thisArg] The `this` binding of `iteratee`.
10036 * @returns {Object} Returns `object`.
10037 * @example
10038 *
10039 * function Foo() {
10040 * this.a = 1;
10041 * this.b = 2;
10042 * }
10043 *
10044 * Foo.prototype.c = 3;
10045 *
10046 * _.forOwn(new Foo, function(value, key) {
10047 * console.log(key);
10048 * });
10049 * // => logs 'a' and 'b' (iteration order is not guaranteed)
10050 */
10051 var forOwn = createForOwn(baseForOwn);
10052
10053 /**
10054 * This method is like `_.forOwn` except that it iterates over properties of
10055 * `object` in the opposite order.
10056 *
10057 * @static
10058 * @memberOf _
10059 * @category Object
10060 * @param {Object} object The object to iterate over.
10061 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
10062 * @param {*} [thisArg] The `this` binding of `iteratee`.
10063 * @returns {Object} Returns `object`.
10064 * @example
10065 *
10066 * function Foo() {
10067 * this.a = 1;
10068 * this.b = 2;
10069 * }
10070 *
10071 * Foo.prototype.c = 3;
10072 *
10073 * _.forOwnRight(new Foo, function(value, key) {
10074 * console.log(key);
10075 * });
10076 * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
10077 */
10078 var forOwnRight = createForOwn(baseForOwnRight);
10079
10080 /**
10081 * Creates an array of function property names from all enumerable properties,
10082 * own and inherited, of `object`.
10083 *
10084 * @static
10085 * @memberOf _
10086 * @alias methods
10087 * @category Object
10088 * @param {Object} object The object to inspect.
10089 * @returns {Array} Returns the new array of property names.
10090 * @example
10091 *
10092 * _.functions(_);
10093 * // => ['after', 'ary', 'assign', ...]
10094 */
10095 function functions(object) {
10096 return baseFunctions(object, keysIn(object));
10097 }
10098
10099 /**
10100 * Gets the property value at `path` of `object`. If the resolved value is
10101 * `undefined` the `defaultValue` is used in its place.
10102 *
10103 * @static
10104 * @memberOf _
10105 * @category Object
10106 * @param {Object} object The object to query.
10107 * @param {Array|string} path The path of the property to get.
10108 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
10109 * @returns {*} Returns the resolved value.
10110 * @example
10111 *
10112 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
10113 *
10114 * _.get(object, 'a[0].b.c');
10115 * // => 3
10116 *
10117 * _.get(object, ['a', '0', 'b', 'c']);
10118 * // => 3
10119 *
10120 * _.get(object, 'a.b.c', 'default');
10121 * // => 'default'
10122 */
10123 function get(object, path, defaultValue) {
10124 var result = object == null ? undefined : baseGet(object, toPath(path), path + '');
10125 return result === undefined ? defaultValue : result;
10126 }
10127
10128 /**
10129 * Checks if `path` is a direct property.
10130 *
10131 * @static
10132 * @memberOf _
10133 * @category Object
10134 * @param {Object} object The object to query.
10135 * @param {Array|string} path The path to check.
10136 * @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
10137 * @example
10138 *
10139 * var object = { 'a': { 'b': { 'c': 3 } } };
10140 *
10141 * _.has(object, 'a');
10142 * // => true
10143 *
10144 * _.has(object, 'a.b.c');
10145 * // => true
10146 *
10147 * _.has(object, ['a', 'b', 'c']);
10148 * // => true
10149 */
10150 function has(object, path) {
10151 if (object == null) {
10152 return false;
10153 }
10154 var result = hasOwnProperty.call(object, path);
10155 if (!result && !isKey(path)) {
10156 path = toPath(path);
10157 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
10158 if (object == null) {
10159 return false;
10160 }
10161 path = last(path);
10162 result = hasOwnProperty.call(object, path);
10163 }
10164 return result || (isLength(object.length) && isIndex(path, object.length) &&
10165 (isArray(object) || isArguments(object)));
10166 }
10167
10168 /**
10169 * Creates an object composed of the inverted keys and values of `object`.
10170 * If `object` contains duplicate values, subsequent values overwrite property
10171 * assignments of previous values unless `multiValue` is `true`.
10172 *
10173 * @static
10174 * @memberOf _
10175 * @category Object
10176 * @param {Object} object The object to invert.
10177 * @param {boolean} [multiValue] Allow multiple values per key.
10178 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
10179 * @returns {Object} Returns the new inverted object.
10180 * @example
10181 *
10182 * var object = { 'a': 1, 'b': 2, 'c': 1 };
10183 *
10184 * _.invert(object);
10185 * // => { '1': 'c', '2': 'b' }
10186 *
10187 * // with `multiValue`
10188 * _.invert(object, true);
10189 * // => { '1': ['a', 'c'], '2': ['b'] }
10190 */
10191 function invert(object, multiValue, guard) {
10192 if (guard && isIterateeCall(object, multiValue, guard)) {
10193 multiValue = undefined;
10194 }
10195 var index = -1,
10196 props = keys(object),
10197 length = props.length,
10198 result = {};
10199
10200 while (++index < length) {
10201 var key = props[index],
10202 value = object[key];
10203
10204 if (multiValue) {
10205 if (hasOwnProperty.call(result, value)) {
10206 result[value].push(key);
10207 } else {
10208 result[value] = [key];
10209 }
10210 }
10211 else {
10212 result[value] = key;
10213 }
10214 }
10215 return result;
10216 }
10217
10218 /**
10219 * Creates an array of the own enumerable property names of `object`.
10220 *
10221 * **Note:** Non-object values are coerced to objects. See the
10222 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
10223 * for more details.
10224 *
10225 * @static
10226 * @memberOf _
10227 * @category Object
10228 * @param {Object} object The object to query.
10229 * @returns {Array} Returns the array of property names.
10230 * @example
10231 *
10232 * function Foo() {
10233 * this.a = 1;
10234 * this.b = 2;
10235 * }
10236 *
10237 * Foo.prototype.c = 3;
10238 *
10239 * _.keys(new Foo);
10240 * // => ['a', 'b'] (iteration order is not guaranteed)
10241 *
10242 * _.keys('hi');
10243 * // => ['0', '1']
10244 */
10245 var keys = !nativeKeys ? shimKeys : function(object) {
10246 var Ctor = object == null ? undefined : object.constructor;
10247 if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
10248 (typeof object != 'function' && isArrayLike(object))) {
10249 return shimKeys(object);
10250 }
10251 return isObject(object) ? nativeKeys(object) : [];
10252 };
10253
10254 /**
10255 * Creates an array of the own and inherited enumerable property names of `object`.
10256 *
10257 * **Note:** Non-object values are coerced to objects.
10258 *
10259 * @static
10260 * @memberOf _
10261 * @category Object
10262 * @param {Object} object The object to query.
10263 * @returns {Array} Returns the array of property names.
10264 * @example
10265 *
10266 * function Foo() {
10267 * this.a = 1;
10268 * this.b = 2;
10269 * }
10270 *
10271 * Foo.prototype.c = 3;
10272 *
10273 * _.keysIn(new Foo);
10274 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
10275 */
10276 function keysIn(object) {
10277 if (object == null) {
10278 return [];
10279 }
10280 if (!isObject(object)) {
10281 object = Object(object);
10282 }
10283 var length = object.length;
10284 length = (length && isLength(length) &&
10285 (isArray(object) || isArguments(object)) && length) || 0;
10286
10287 var Ctor = object.constructor,
10288 index = -1,
10289 isProto = typeof Ctor == 'function' && Ctor.prototype === object,
10290 result = Array(length),
10291 skipIndexes = length > 0;
10292
10293 while (++index < length) {
10294 result[index] = (index + '');
10295 }
10296 for (var key in object) {
10297 if (!(skipIndexes && isIndex(key, length)) &&
10298 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
10299 result.push(key);
10300 }
10301 }
10302 return result;
10303 }
10304
10305 /**
10306 * The opposite of `_.mapValues`; this method creates an object with the
10307 * same values as `object` and keys generated by running each own enumerable
10308 * property of `object` through `iteratee`.
10309 *
10310 * @static
10311 * @memberOf _
10312 * @category Object
10313 * @param {Object} object The object to iterate over.
10314 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
10315 * per iteration.
10316 * @param {*} [thisArg] The `this` binding of `iteratee`.
10317 * @returns {Object} Returns the new mapped object.
10318 * @example
10319 *
10320 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
10321 * return key + value;
10322 * });
10323 * // => { 'a1': 1, 'b2': 2 }
10324 */
10325 var mapKeys = createObjectMapper(true);
10326
10327 /**
10328 * Creates an object with the same keys as `object` and values generated by
10329 * running each own enumerable property of `object` through `iteratee`. The
10330 * iteratee function is bound to `thisArg` and invoked with three arguments:
10331 * (value, key, object).
10332 *
10333 * If a property name is provided for `iteratee` the created `_.property`
10334 * style callback returns the property value of the given element.
10335 *
10336 * If a value is also provided for `thisArg` the created `_.matchesProperty`
10337 * style callback returns `true` for elements that have a matching property
10338 * value, else `false`.
10339 *
10340 * If an object is provided for `iteratee` the created `_.matches` style
10341 * callback returns `true` for elements that have the properties of the given
10342 * object, else `false`.
10343 *
10344 * @static
10345 * @memberOf _
10346 * @category Object
10347 * @param {Object} object The object to iterate over.
10348 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
10349 * per iteration.
10350 * @param {*} [thisArg] The `this` binding of `iteratee`.
10351 * @returns {Object} Returns the new mapped object.
10352 * @example
10353 *
10354 * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
10355 * return n * 3;
10356 * });
10357 * // => { 'a': 3, 'b': 6 }
10358 *
10359 * var users = {
10360 * 'fred': { 'user': 'fred', 'age': 40 },
10361 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
10362 * };
10363 *
10364 * // using the `_.property` callback shorthand
10365 * _.mapValues(users, 'age');
10366 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
10367 */
10368 var mapValues = createObjectMapper();
10369
10370 /**
10371 * The opposite of `_.pick`; this method creates an object composed of the
10372 * own and inherited enumerable properties of `object` that are not omitted.
10373 *
10374 * @static
10375 * @memberOf _
10376 * @category Object
10377 * @param {Object} object The source object.
10378 * @param {Function|...(string|string[])} [predicate] The function invoked per
10379 * iteration or property names to omit, specified as individual property
10380 * names or arrays of property names.
10381 * @param {*} [thisArg] The `this` binding of `predicate`.
10382 * @returns {Object} Returns the new object.
10383 * @example
10384 *
10385 * var object = { 'user': 'fred', 'age': 40 };
10386 *
10387 * _.omit(object, 'age');
10388 * // => { 'user': 'fred' }
10389 *
10390 * _.omit(object, _.isNumber);
10391 * // => { 'user': 'fred' }
10392 */
10393 var omit = restParam(function(object, props) {
10394 if (object == null) {
10395 return {};
10396 }
10397 if (typeof props[0] != 'function') {
10398 var props = arrayMap(baseFlatten(props), String);
10399 return pickByArray(object, baseDifference(keysIn(object), props));
10400 }
10401 var predicate = bindCallback(props[0], props[1], 3);
10402 return pickByCallback(object, function(value, key, object) {
10403 return !predicate(value, key, object);
10404 });
10405 });
10406
10407 /**
10408 * Creates a two dimensional array of the key-value pairs for `object`,
10409 * e.g. `[[key1, value1], [key2, value2]]`.
10410 *
10411 * @static
10412 * @memberOf _
10413 * @category Object
10414 * @param {Object} object The object to query.
10415 * @returns {Array} Returns the new array of key-value pairs.
10416 * @example
10417 *
10418 * _.pairs({ 'barney': 36, 'fred': 40 });
10419 * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
10420 */
10421 function pairs(object) {
10422 object = toObject(object);
10423
10424 var index = -1,
10425 props = keys(object),
10426 length = props.length,
10427 result = Array(length);
10428
10429 while (++index < length) {
10430 var key = props[index];
10431 result[index] = [key, object[key]];
10432 }
10433 return result;
10434 }
10435
10436 /**
10437 * Creates an object composed of the picked `object` properties. Property
10438 * names may be specified as individual arguments or as arrays of property
10439 * names. If `predicate` is provided it is invoked for each property of `object`
10440 * picking the properties `predicate` returns truthy for. The predicate is
10441 * bound to `thisArg` and invoked with three arguments: (value, key, object).
10442 *
10443 * @static
10444 * @memberOf _
10445 * @category Object
10446 * @param {Object} object The source object.
10447 * @param {Function|...(string|string[])} [predicate] The function invoked per
10448 * iteration or property names to pick, specified as individual property
10449 * names or arrays of property names.
10450 * @param {*} [thisArg] The `this` binding of `predicate`.
10451 * @returns {Object} Returns the new object.
10452 * @example
10453 *
10454 * var object = { 'user': 'fred', 'age': 40 };
10455 *
10456 * _.pick(object, 'user');
10457 * // => { 'user': 'fred' }
10458 *
10459 * _.pick(object, _.isString);
10460 * // => { 'user': 'fred' }
10461 */
10462 var pick = restParam(function(object, props) {
10463 if (object == null) {
10464 return {};
10465 }
10466 return typeof props[0] == 'function'
10467 ? pickByCallback(object, bindCallback(props[0], props[1], 3))
10468 : pickByArray(object, baseFlatten(props));
10469 });
10470
10471 /**
10472 * This method is like `_.get` except that if the resolved value is a function
10473 * it is invoked with the `this` binding of its parent object and its result
10474 * is returned.
10475 *
10476 * @static
10477 * @memberOf _
10478 * @category Object
10479 * @param {Object} object The object to query.
10480 * @param {Array|string} path The path of the property to resolve.
10481 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
10482 * @returns {*} Returns the resolved value.
10483 * @example
10484 *
10485 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
10486 *
10487 * _.result(object, 'a[0].b.c1');
10488 * // => 3
10489 *
10490 * _.result(object, 'a[0].b.c2');
10491 * // => 4
10492 *
10493 * _.result(object, 'a.b.c', 'default');
10494 * // => 'default'
10495 *
10496 * _.result(object, 'a.b.c', _.constant('default'));
10497 * // => 'default'
10498 */
10499 function result(object, path, defaultValue) {
10500 var result = object == null ? undefined : object[path];
10501 if (result === undefined) {
10502 if (object != null && !isKey(path, object)) {
10503 path = toPath(path);
10504 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
10505 result = object == null ? undefined : object[last(path)];
10506 }
10507 result = result === undefined ? defaultValue : result;
10508 }
10509 return isFunction(result) ? result.call(object) : result;
10510 }
10511
10512 /**
10513 * Sets the property value of `path` on `object`. If a portion of `path`
10514 * does not exist it is created.
10515 *
10516 * @static
10517 * @memberOf _
10518 * @category Object
10519 * @param {Object} object The object to augment.
10520 * @param {Array|string} path The path of the property to set.
10521 * @param {*} value The value to set.
10522 * @returns {Object} Returns `object`.
10523 * @example
10524 *
10525 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
10526 *
10527 * _.set(object, 'a[0].b.c', 4);
10528 * console.log(object.a[0].b.c);
10529 * // => 4
10530 *
10531 * _.set(object, 'x[0].y.z', 5);
10532 * console.log(object.x[0].y.z);
10533 * // => 5
10534 */
10535 function set(object, path, value) {
10536 if (object == null) {
10537 return object;
10538 }
10539 var pathKey = (path + '');
10540 path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
10541
10542 var index = -1,
10543 length = path.length,
10544 lastIndex = length - 1,
10545 nested = object;
10546
10547 while (nested != null && ++index < length) {
10548 var key = path[index];
10549 if (isObject(nested)) {
10550 if (index == lastIndex) {
10551 nested[key] = value;
10552 } else if (nested[key] == null) {
10553 nested[key] = isIndex(path[index + 1]) ? [] : {};
10554 }
10555 }
10556 nested = nested[key];
10557 }
10558 return object;
10559 }
10560
10561 /**
10562 * An alternative to `_.reduce`; this method transforms `object` to a new
10563 * `accumulator` object which is the result of running each of its own enumerable
10564 * properties through `iteratee`, with each invocation potentially mutating
10565 * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
10566 * with four arguments: (accumulator, value, key, object). Iteratee functions
10567 * may exit iteration early by explicitly returning `false`.
10568 *
10569 * @static
10570 * @memberOf _
10571 * @category Object
10572 * @param {Array|Object} object The object to iterate over.
10573 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
10574 * @param {*} [accumulator] The custom accumulator value.
10575 * @param {*} [thisArg] The `this` binding of `iteratee`.
10576 * @returns {*} Returns the accumulated value.
10577 * @example
10578 *
10579 * _.transform([2, 3, 4], function(result, n) {
10580 * result.push(n *= n);
10581 * return n % 2 == 0;
10582 * });
10583 * // => [4, 9]
10584 *
10585 * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
10586 * result[key] = n * 3;
10587 * });
10588 * // => { 'a': 3, 'b': 6 }
10589 */
10590 function transform(object, iteratee, accumulator, thisArg) {
10591 var isArr = isArray(object) || isTypedArray(object);
10592 iteratee = getCallback(iteratee, thisArg, 4);
10593
10594 if (accumulator == null) {
10595 if (isArr || isObject(object)) {
10596 var Ctor = object.constructor;
10597 if (isArr) {
10598 accumulator = isArray(object) ? new Ctor : [];
10599 } else {
10600 accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
10601 }
10602 } else {
10603 accumulator = {};
10604 }
10605 }
10606 (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
10607 return iteratee(accumulator, value, index, object);
10608 });
10609 return accumulator;
10610 }
10611
10612 /**
10613 * Creates an array of the own enumerable property values of `object`.
10614 *
10615 * **Note:** Non-object values are coerced to objects.
10616 *
10617 * @static
10618 * @memberOf _
10619 * @category Object
10620 * @param {Object} object The object to query.
10621 * @returns {Array} Returns the array of property values.
10622 * @example
10623 *
10624 * function Foo() {
10625 * this.a = 1;
10626 * this.b = 2;
10627 * }
10628 *
10629 * Foo.prototype.c = 3;
10630 *
10631 * _.values(new Foo);
10632 * // => [1, 2] (iteration order is not guaranteed)
10633 *
10634 * _.values('hi');
10635 * // => ['h', 'i']
10636 */
10637 function values(object) {
10638 return baseValues(object, keys(object));
10639 }
10640
10641 /**
10642 * Creates an array of the own and inherited enumerable property values
10643 * of `object`.
10644 *
10645 * **Note:** Non-object values are coerced to objects.
10646 *
10647 * @static
10648 * @memberOf _
10649 * @category Object
10650 * @param {Object} object The object to query.
10651 * @returns {Array} Returns the array of property values.
10652 * @example
10653 *
10654 * function Foo() {
10655 * this.a = 1;
10656 * this.b = 2;
10657 * }
10658 *
10659 * Foo.prototype.c = 3;
10660 *
10661 * _.valuesIn(new Foo);
10662 * // => [1, 2, 3] (iteration order is not guaranteed)
10663 */
10664 function valuesIn(object) {
10665 return baseValues(object, keysIn(object));
10666 }
10667
10668 /*------------------------------------------------------------------------*/
10669
10670 /**
10671 * Checks if `n` is between `start` and up to but not including, `end`. If
10672 * `end` is not specified it is set to `start` with `start` then set to `0`.
10673 *
10674 * @static
10675 * @memberOf _
10676 * @category Number
10677 * @param {number} n The number to check.
10678 * @param {number} [start=0] The start of the range.
10679 * @param {number} end The end of the range.
10680 * @returns {boolean} Returns `true` if `n` is in the range, else `false`.
10681 * @example
10682 *
10683 * _.inRange(3, 2, 4);
10684 * // => true
10685 *
10686 * _.inRange(4, 8);
10687 * // => true
10688 *
10689 * _.inRange(4, 2);
10690 * // => false
10691 *
10692 * _.inRange(2, 2);
10693 * // => false
10694 *
10695 * _.inRange(1.2, 2);
10696 * // => true
10697 *
10698 * _.inRange(5.2, 4);
10699 * // => false
10700 */
10701 function inRange(value, start, end) {
10702 start = +start || 0;
10703 if (end === undefined) {
10704 end = start;
10705 start = 0;
10706 } else {
10707 end = +end || 0;
10708 }
10709 return value >= nativeMin(start, end) && value < nativeMax(start, end);
10710 }
10711
10712 /**
10713 * Produces a random number between `min` and `max` (inclusive). If only one
10714 * argument is provided a number between `0` and the given number is returned.
10715 * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
10716 * number is returned instead of an integer.
10717 *
10718 * @static
10719 * @memberOf _
10720 * @category Number
10721 * @param {number} [min=0] The minimum possible value.
10722 * @param {number} [max=1] The maximum possible value.
10723 * @param {boolean} [floating] Specify returning a floating-point number.
10724 * @returns {number} Returns the random number.
10725 * @example
10726 *
10727 * _.random(0, 5);
10728 * // => an integer between 0 and 5
10729 *
10730 * _.random(5);
10731 * // => also an integer between 0 and 5
10732 *
10733 * _.random(5, true);
10734 * // => a floating-point number between 0 and 5
10735 *
10736 * _.random(1.2, 5.2);
10737 * // => a floating-point number between 1.2 and 5.2
10738 */
10739 function random(min, max, floating) {
10740 if (floating && isIterateeCall(min, max, floating)) {
10741 max = floating = undefined;
10742 }
10743 var noMin = min == null,
10744 noMax = max == null;
10745
10746 if (floating == null) {
10747 if (noMax && typeof min == 'boolean') {
10748 floating = min;
10749 min = 1;
10750 }
10751 else if (typeof max == 'boolean') {
10752 floating = max;
10753 noMax = true;
10754 }
10755 }
10756 if (noMin && noMax) {
10757 max = 1;
10758 noMax = false;
10759 }
10760 min = +min || 0;
10761 if (noMax) {
10762 max = min;
10763 min = 0;
10764 } else {
10765 max = +max || 0;
10766 }
10767 if (floating || min % 1 || max % 1) {
10768 var rand = nativeRandom();
10769 return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
10770 }
10771 return baseRandom(min, max);
10772 }
10773
10774 /*------------------------------------------------------------------------*/
10775
10776 /**
10777 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
10778 *
10779 * @static
10780 * @memberOf _
10781 * @category String
10782 * @param {string} [string=''] The string to convert.
10783 * @returns {string} Returns the camel cased string.
10784 * @example
10785 *
10786 * _.camelCase('Foo Bar');
10787 * // => 'fooBar'
10788 *
10789 * _.camelCase('--foo-bar');
10790 * // => 'fooBar'
10791 *
10792 * _.camelCase('__foo_bar__');
10793 * // => 'fooBar'
10794 */
10795 var camelCase = createCompounder(function(result, word, index) {
10796 word = word.toLowerCase();
10797 return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
10798 });
10799
10800 /**
10801 * Capitalizes the first character of `string`.
10802 *
10803 * @static
10804 * @memberOf _
10805 * @category String
10806 * @param {string} [string=''] The string to capitalize.
10807 * @returns {string} Returns the capitalized string.
10808 * @example
10809 *
10810 * _.capitalize('fred');
10811 * // => 'Fred'
10812 */
10813 function capitalize(string) {
10814 string = baseToString(string);
10815 return string && (string.charAt(0).toUpperCase() + string.slice(1));
10816 }
10817
10818 /**
10819 * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
10820 * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
10821 *
10822 * @static
10823 * @memberOf _
10824 * @category String
10825 * @param {string} [string=''] The string to deburr.
10826 * @returns {string} Returns the deburred string.
10827 * @example
10828 *
10829 * _.deburr('déjà vu');
10830 * // => 'deja vu'
10831 */
10832 function deburr(string) {
10833 string = baseToString(string);
10834 return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
10835 }
10836
10837 /**
10838 * Checks if `string` ends with the given target string.
10839 *
10840 * @static
10841 * @memberOf _
10842 * @category String
10843 * @param {string} [string=''] The string to search.
10844 * @param {string} [target] The string to search for.
10845 * @param {number} [position=string.length] The position to search from.
10846 * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
10847 * @example
10848 *
10849 * _.endsWith('abc', 'c');
10850 * // => true
10851 *
10852 * _.endsWith('abc', 'b');
10853 * // => false
10854 *
10855 * _.endsWith('abc', 'b', 2);
10856 * // => true
10857 */
10858 function endsWith(string, target, position) {
10859 string = baseToString(string);
10860 target = (target + '');
10861
10862 var length = string.length;
10863 position = position === undefined
10864 ? length
10865 : nativeMin(position < 0 ? 0 : (+position || 0), length);
10866
10867 position -= target.length;
10868 return position >= 0 && string.indexOf(target, position) == position;
10869 }
10870
10871 /**
10872 * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
10873 * their corresponding HTML entities.
10874 *
10875 * **Note:** No other characters are escaped. To escape additional characters
10876 * use a third-party library like [_he_](https://mths.be/he).
10877 *
10878 * Though the ">" character is escaped for symmetry, characters like
10879 * ">" and "/" don't need escaping in HTML and have no special meaning
10880 * unless they're part of a tag or unquoted attribute value.
10881 * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
10882 * (under "semi-related fun fact") for more details.
10883 *
10884 * Backticks are escaped because in Internet Explorer < 9, they can break out
10885 * of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
10886 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
10887 * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
10888 * for more details.
10889 *
10890 * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
10891 * to reduce XSS vectors.
10892 *
10893 * @static
10894 * @memberOf _
10895 * @category String
10896 * @param {string} [string=''] The string to escape.
10897 * @returns {string} Returns the escaped string.
10898 * @example
10899 *
10900 * _.escape('fred, barney, & pebbles');
10901 * // => 'fred, barney, &amp; pebbles'
10902 */
10903 function escape(string) {
10904 // Reset `lastIndex` because in IE < 9 `String#replace` does not.
10905 string = baseToString(string);
10906 return (string && reHasUnescapedHtml.test(string))
10907 ? string.replace(reUnescapedHtml, escapeHtmlChar)
10908 : string;
10909 }
10910
10911 /**
10912 * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
10913 * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
10914 *
10915 * @static
10916 * @memberOf _
10917 * @category String
10918 * @param {string} [string=''] The string to escape.
10919 * @returns {string} Returns the escaped string.
10920 * @example
10921 *
10922 * _.escapeRegExp('[lodash](https://lodash.com/)');
10923 * // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
10924 */
10925 function escapeRegExp(string) {
10926 string = baseToString(string);
10927 return (string && reHasRegExpChars.test(string))
10928 ? string.replace(reRegExpChars, escapeRegExpChar)
10929 : (string || '(?:)');
10930 }
10931
10932 /**
10933 * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
10934 *
10935 * @static
10936 * @memberOf _
10937 * @category String
10938 * @param {string} [string=''] The string to convert.
10939 * @returns {string} Returns the kebab cased string.
10940 * @example
10941 *
10942 * _.kebabCase('Foo Bar');
10943 * // => 'foo-bar'
10944 *
10945 * _.kebabCase('fooBar');
10946 * // => 'foo-bar'
10947 *
10948 * _.kebabCase('__foo_bar__');
10949 * // => 'foo-bar'
10950 */
10951 var kebabCase = createCompounder(function(result, word, index) {
10952 return result + (index ? '-' : '') + word.toLowerCase();
10953 });
10954
10955 /**
10956 * Pads `string` on the left and right sides if it's shorter than `length`.
10957 * Padding characters are truncated if they can't be evenly divided by `length`.
10958 *
10959 * @static
10960 * @memberOf _
10961 * @category String
10962 * @param {string} [string=''] The string to pad.
10963 * @param {number} [length=0] The padding length.
10964 * @param {string} [chars=' '] The string used as padding.
10965 * @returns {string} Returns the padded string.
10966 * @example
10967 *
10968 * _.pad('abc', 8);
10969 * // => ' abc '
10970 *
10971 * _.pad('abc', 8, '_-');
10972 * // => '_-abc_-_'
10973 *
10974 * _.pad('abc', 3);
10975 * // => 'abc'
10976 */
10977 function pad(string, length, chars) {
10978 string = baseToString(string);
10979 length = +length;
10980
10981 var strLength = string.length;
10982 if (strLength >= length || !nativeIsFinite(length)) {
10983 return string;
10984 }
10985 var mid = (length - strLength) / 2,
10986 leftLength = nativeFloor(mid),
10987 rightLength = nativeCeil(mid);
10988
10989 chars = createPadding('', rightLength, chars);
10990 return chars.slice(0, leftLength) + string + chars;
10991 }
10992
10993 /**
10994 * Pads `string` on the left side if it's shorter than `length`. Padding
10995 * characters are truncated if they exceed `length`.
10996 *
10997 * @static
10998 * @memberOf _
10999 * @category String
11000 * @param {string} [string=''] The string to pad.
11001 * @param {number} [length=0] The padding length.
11002 * @param {string} [chars=' '] The string used as padding.
11003 * @returns {string} Returns the padded string.
11004 * @example
11005 *
11006 * _.padLeft('abc', 6);
11007 * // => ' abc'
11008 *
11009 * _.padLeft('abc', 6, '_-');
11010 * // => '_-_abc'
11011 *
11012 * _.padLeft('abc', 3);
11013 * // => 'abc'
11014 */
11015 var padLeft = createPadDir();
11016
11017 /**
11018 * Pads `string` on the right side if it's shorter than `length`. Padding
11019 * characters are truncated if they exceed `length`.
11020 *
11021 * @static
11022 * @memberOf _
11023 * @category String
11024 * @param {string} [string=''] The string to pad.
11025 * @param {number} [length=0] The padding length.
11026 * @param {string} [chars=' '] The string used as padding.
11027 * @returns {string} Returns the padded string.
11028 * @example
11029 *
11030 * _.padRight('abc', 6);
11031 * // => 'abc '
11032 *
11033 * _.padRight('abc', 6, '_-');
11034 * // => 'abc_-_'
11035 *
11036 * _.padRight('abc', 3);
11037 * // => 'abc'
11038 */
11039 var padRight = createPadDir(true);
11040
11041 /**
11042 * Converts `string` to an integer of the specified radix. If `radix` is
11043 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
11044 * in which case a `radix` of `16` is used.
11045 *
11046 * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
11047 * of `parseInt`.
11048 *
11049 * @static
11050 * @memberOf _
11051 * @category String
11052 * @param {string} string The string to convert.
11053 * @param {number} [radix] The radix to interpret `value` by.
11054 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11055 * @returns {number} Returns the converted integer.
11056 * @example
11057 *
11058 * _.parseInt('08');
11059 * // => 8
11060 *
11061 * _.map(['6', '08', '10'], _.parseInt);
11062 * // => [6, 8, 10]
11063 */
11064 function parseInt(string, radix, guard) {
11065 // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
11066 // Chrome fails to trim leading <BOM> whitespace characters.
11067 // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
11068 if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
11069 radix = 0;
11070 } else if (radix) {
11071 radix = +radix;
11072 }
11073 string = trim(string);
11074 return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
11075 }
11076
11077 /**
11078 * Repeats the given string `n` times.
11079 *
11080 * @static
11081 * @memberOf _
11082 * @category String
11083 * @param {string} [string=''] The string to repeat.
11084 * @param {number} [n=0] The number of times to repeat the string.
11085 * @returns {string} Returns the repeated string.
11086 * @example
11087 *
11088 * _.repeat('*', 3);
11089 * // => '***'
11090 *
11091 * _.repeat('abc', 2);
11092 * // => 'abcabc'
11093 *
11094 * _.repeat('abc', 0);
11095 * // => ''
11096 */
11097 function repeat(string, n) {
11098 var result = '';
11099 string = baseToString(string);
11100 n = +n;
11101 if (n < 1 || !string || !nativeIsFinite(n)) {
11102 return result;
11103 }
11104 // Leverage the exponentiation by squaring algorithm for a faster repeat.
11105 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
11106 do {
11107 if (n % 2) {
11108 result += string;
11109 }
11110 n = nativeFloor(n / 2);
11111 string += string;
11112 } while (n);
11113
11114 return result;
11115 }
11116
11117 /**
11118 * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
11119 *
11120 * @static
11121 * @memberOf _
11122 * @category String
11123 * @param {string} [string=''] The string to convert.
11124 * @returns {string} Returns the snake cased string.
11125 * @example
11126 *
11127 * _.snakeCase('Foo Bar');
11128 * // => 'foo_bar'
11129 *
11130 * _.snakeCase('fooBar');
11131 * // => 'foo_bar'
11132 *
11133 * _.snakeCase('--foo-bar');
11134 * // => 'foo_bar'
11135 */
11136 var snakeCase = createCompounder(function(result, word, index) {
11137 return result + (index ? '_' : '') + word.toLowerCase();
11138 });
11139
11140 /**
11141 * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
11142 *
11143 * @static
11144 * @memberOf _
11145 * @category String
11146 * @param {string} [string=''] The string to convert.
11147 * @returns {string} Returns the start cased string.
11148 * @example
11149 *
11150 * _.startCase('--foo-bar');
11151 * // => 'Foo Bar'
11152 *
11153 * _.startCase('fooBar');
11154 * // => 'Foo Bar'
11155 *
11156 * _.startCase('__foo_bar__');
11157 * // => 'Foo Bar'
11158 */
11159 var startCase = createCompounder(function(result, word, index) {
11160 return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
11161 });
11162
11163 /**
11164 * Checks if `string` starts with the given target string.
11165 *
11166 * @static
11167 * @memberOf _
11168 * @category String
11169 * @param {string} [string=''] The string to search.
11170 * @param {string} [target] The string to search for.
11171 * @param {number} [position=0] The position to search from.
11172 * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
11173 * @example
11174 *
11175 * _.startsWith('abc', 'a');
11176 * // => true
11177 *
11178 * _.startsWith('abc', 'b');
11179 * // => false
11180 *
11181 * _.startsWith('abc', 'b', 1);
11182 * // => true
11183 */
11184 function startsWith(string, target, position) {
11185 string = baseToString(string);
11186 position = position == null
11187 ? 0
11188 : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
11189
11190 return string.lastIndexOf(target, position) == position;
11191 }
11192
11193 /**
11194 * Creates a compiled template function that can interpolate data properties
11195 * in "interpolate" delimiters, HTML-escape interpolated data properties in
11196 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
11197 * properties may be accessed as free variables in the template. If a setting
11198 * object is provided it takes precedence over `_.templateSettings` values.
11199 *
11200 * **Note:** In the development build `_.template` utilizes
11201 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
11202 * for easier debugging.
11203 *
11204 * For more information on precompiling templates see
11205 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
11206 *
11207 * For more information on Chrome extension sandboxes see
11208 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
11209 *
11210 * @static
11211 * @memberOf _
11212 * @category String
11213 * @param {string} [string=''] The template string.
11214 * @param {Object} [options] The options object.
11215 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
11216 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
11217 * @param {Object} [options.imports] An object to import into the template as free variables.
11218 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
11219 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
11220 * @param {string} [options.variable] The data object variable name.
11221 * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
11222 * @returns {Function} Returns the compiled template function.
11223 * @example
11224 *
11225 * // using the "interpolate" delimiter to create a compiled template
11226 * var compiled = _.template('hello <%= user %>!');
11227 * compiled({ 'user': 'fred' });
11228 * // => 'hello fred!'
11229 *
11230 * // using the HTML "escape" delimiter to escape data property values
11231 * var compiled = _.template('<b><%- value %></b>');
11232 * compiled({ 'value': '<script>' });
11233 * // => '<b>&lt;script&gt;</b>'
11234 *
11235 * // using the "evaluate" delimiter to execute JavaScript and generate HTML
11236 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
11237 * compiled({ 'users': ['fred', 'barney'] });
11238 * // => '<li>fred</li><li>barney</li>'
11239 *
11240 * // using the internal `print` function in "evaluate" delimiters
11241 * var compiled = _.template('<% print("hello " + user); %>!');
11242 * compiled({ 'user': 'barney' });
11243 * // => 'hello barney!'
11244 *
11245 * // using the ES delimiter as an alternative to the default "interpolate" delimiter
11246 * var compiled = _.template('hello ${ user }!');
11247 * compiled({ 'user': 'pebbles' });
11248 * // => 'hello pebbles!'
11249 *
11250 * // using custom template delimiters
11251 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
11252 * var compiled = _.template('hello {{ user }}!');
11253 * compiled({ 'user': 'mustache' });
11254 * // => 'hello mustache!'
11255 *
11256 * // using backslashes to treat delimiters as plain text
11257 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
11258 * compiled({ 'value': 'ignored' });
11259 * // => '<%- value %>'
11260 *
11261 * // using the `imports` option to import `jQuery` as `jq`
11262 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
11263 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
11264 * compiled({ 'users': ['fred', 'barney'] });
11265 * // => '<li>fred</li><li>barney</li>'
11266 *
11267 * // using the `sourceURL` option to specify a custom sourceURL for the template
11268 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
11269 * compiled(data);
11270 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
11271 *
11272 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
11273 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
11274 * compiled.source;
11275 * // => function(data) {
11276 * // var __t, __p = '';
11277 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
11278 * // return __p;
11279 * // }
11280 *
11281 * // using the `source` property to inline compiled templates for meaningful
11282 * // line numbers in error messages and a stack trace
11283 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
11284 * var JST = {\
11285 * "main": ' + _.template(mainText).source + '\
11286 * };\
11287 * ');
11288 */
11289 function template(string, options, otherOptions) {
11290 // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
11291 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
11292 var settings = lodash.templateSettings;
11293
11294 if (otherOptions && isIterateeCall(string, options, otherOptions)) {
11295 options = otherOptions = undefined;
11296 }
11297 string = baseToString(string);
11298 options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
11299
11300 var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
11301 importsKeys = keys(imports),
11302 importsValues = baseValues(imports, importsKeys);
11303
11304 var isEscaping,
11305 isEvaluating,
11306 index = 0,
11307 interpolate = options.interpolate || reNoMatch,
11308 source = "__p += '";
11309
11310 // Compile the regexp to match each delimiter.
11311 var reDelimiters = RegExp(
11312 (options.escape || reNoMatch).source + '|' +
11313 interpolate.source + '|' +
11314 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
11315 (options.evaluate || reNoMatch).source + '|$'
11316 , 'g');
11317
11318 // Use a sourceURL for easier debugging.
11319 var sourceURL = '//# sourceURL=' +
11320 ('sourceURL' in options
11321 ? options.sourceURL
11322 : ('lodash.templateSources[' + (++templateCounter) + ']')
11323 ) + '\n';
11324
11325 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
11326 interpolateValue || (interpolateValue = esTemplateValue);
11327
11328 // Escape characters that can't be included in string literals.
11329 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
11330
11331 // Replace delimiters with snippets.
11332 if (escapeValue) {
11333 isEscaping = true;
11334 source += "' +\n__e(" + escapeValue + ") +\n'";
11335 }
11336 if (evaluateValue) {
11337 isEvaluating = true;
11338 source += "';\n" + evaluateValue + ";\n__p += '";
11339 }
11340 if (interpolateValue) {
11341 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
11342 }
11343 index = offset + match.length;
11344
11345 // The JS engine embedded in Adobe products requires returning the `match`
11346 // string in order to produce the correct `offset` value.
11347 return match;
11348 });
11349
11350 source += "';\n";
11351
11352 // If `variable` is not specified wrap a with-statement around the generated
11353 // code to add the data object to the top of the scope chain.
11354 var variable = options.variable;
11355 if (!variable) {
11356 source = 'with (obj) {\n' + source + '\n}\n';
11357 }
11358 // Cleanup code by stripping empty strings.
11359 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
11360 .replace(reEmptyStringMiddle, '$1')
11361 .replace(reEmptyStringTrailing, '$1;');
11362
11363 // Frame code as the function body.
11364 source = 'function(' + (variable || 'obj') + ') {\n' +
11365 (variable
11366 ? ''
11367 : 'obj || (obj = {});\n'
11368 ) +
11369 "var __t, __p = ''" +
11370 (isEscaping
11371 ? ', __e = _.escape'
11372 : ''
11373 ) +
11374 (isEvaluating
11375 ? ', __j = Array.prototype.join;\n' +
11376 "function print() { __p += __j.call(arguments, '') }\n"
11377 : ';\n'
11378 ) +
11379 source +
11380 'return __p\n}';
11381
11382 var result = attempt(function() {
11383 return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
11384 });
11385
11386 // Provide the compiled function's source by its `toString` method or
11387 // the `source` property as a convenience for inlining compiled templates.
11388 result.source = source;
11389 if (isError(result)) {
11390 throw result;
11391 }
11392 return result;
11393 }
11394
11395 /**
11396 * Removes leading and trailing whitespace or specified characters from `string`.
11397 *
11398 * @static
11399 * @memberOf _
11400 * @category String
11401 * @param {string} [string=''] The string to trim.
11402 * @param {string} [chars=whitespace] The characters to trim.
11403 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11404 * @returns {string} Returns the trimmed string.
11405 * @example
11406 *
11407 * _.trim(' abc ');
11408 * // => 'abc'
11409 *
11410 * _.trim('-_-abc-_-', '_-');
11411 * // => 'abc'
11412 *
11413 * _.map([' foo ', ' bar '], _.trim);
11414 * // => ['foo', 'bar']
11415 */
11416 function trim(string, chars, guard) {
11417 var value = string;
11418 string = baseToString(string);
11419 if (!string) {
11420 return string;
11421 }
11422 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
11423 return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
11424 }
11425 chars = (chars + '');
11426 return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
11427 }
11428
11429 /**
11430 * Removes leading whitespace or specified characters from `string`.
11431 *
11432 * @static
11433 * @memberOf _
11434 * @category String
11435 * @param {string} [string=''] The string to trim.
11436 * @param {string} [chars=whitespace] The characters to trim.
11437 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11438 * @returns {string} Returns the trimmed string.
11439 * @example
11440 *
11441 * _.trimLeft(' abc ');
11442 * // => 'abc '
11443 *
11444 * _.trimLeft('-_-abc-_-', '_-');
11445 * // => 'abc-_-'
11446 */
11447 function trimLeft(string, chars, guard) {
11448 var value = string;
11449 string = baseToString(string);
11450 if (!string) {
11451 return string;
11452 }
11453 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
11454 return string.slice(trimmedLeftIndex(string));
11455 }
11456 return string.slice(charsLeftIndex(string, (chars + '')));
11457 }
11458
11459 /**
11460 * Removes trailing whitespace or specified characters from `string`.
11461 *
11462 * @static
11463 * @memberOf _
11464 * @category String
11465 * @param {string} [string=''] The string to trim.
11466 * @param {string} [chars=whitespace] The characters to trim.
11467 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11468 * @returns {string} Returns the trimmed string.
11469 * @example
11470 *
11471 * _.trimRight(' abc ');
11472 * // => ' abc'
11473 *
11474 * _.trimRight('-_-abc-_-', '_-');
11475 * // => '-_-abc'
11476 */
11477 function trimRight(string, chars, guard) {
11478 var value = string;
11479 string = baseToString(string);
11480 if (!string) {
11481 return string;
11482 }
11483 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
11484 return string.slice(0, trimmedRightIndex(string) + 1);
11485 }
11486 return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
11487 }
11488
11489 /**
11490 * Truncates `string` if it's longer than the given maximum string length.
11491 * The last characters of the truncated string are replaced with the omission
11492 * string which defaults to "...".
11493 *
11494 * @static
11495 * @memberOf _
11496 * @category String
11497 * @param {string} [string=''] The string to truncate.
11498 * @param {Object|number} [options] The options object or maximum string length.
11499 * @param {number} [options.length=30] The maximum string length.
11500 * @param {string} [options.omission='...'] The string to indicate text is omitted.
11501 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
11502 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11503 * @returns {string} Returns the truncated string.
11504 * @example
11505 *
11506 * _.trunc('hi-diddly-ho there, neighborino');
11507 * // => 'hi-diddly-ho there, neighbo...'
11508 *
11509 * _.trunc('hi-diddly-ho there, neighborino', 24);
11510 * // => 'hi-diddly-ho there, n...'
11511 *
11512 * _.trunc('hi-diddly-ho there, neighborino', {
11513 * 'length': 24,
11514 * 'separator': ' '
11515 * });
11516 * // => 'hi-diddly-ho there,...'
11517 *
11518 * _.trunc('hi-diddly-ho there, neighborino', {
11519 * 'length': 24,
11520 * 'separator': /,? +/
11521 * });
11522 * // => 'hi-diddly-ho there...'
11523 *
11524 * _.trunc('hi-diddly-ho there, neighborino', {
11525 * 'omission': ' [...]'
11526 * });
11527 * // => 'hi-diddly-ho there, neig [...]'
11528 */
11529 function trunc(string, options, guard) {
11530 if (guard && isIterateeCall(string, options, guard)) {
11531 options = undefined;
11532 }
11533 var length = DEFAULT_TRUNC_LENGTH,
11534 omission = DEFAULT_TRUNC_OMISSION;
11535
11536 if (options != null) {
11537 if (isObject(options)) {
11538 var separator = 'separator' in options ? options.separator : separator;
11539 length = 'length' in options ? (+options.length || 0) : length;
11540 omission = 'omission' in options ? baseToString(options.omission) : omission;
11541 } else {
11542 length = +options || 0;
11543 }
11544 }
11545 string = baseToString(string);
11546 if (length >= string.length) {
11547 return string;
11548 }
11549 var end = length - omission.length;
11550 if (end < 1) {
11551 return omission;
11552 }
11553 var result = string.slice(0, end);
11554 if (separator == null) {
11555 return result + omission;
11556 }
11557 if (isRegExp(separator)) {
11558 if (string.slice(end).search(separator)) {
11559 var match,
11560 newEnd,
11561 substring = string.slice(0, end);
11562
11563 if (!separator.global) {
11564 separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
11565 }
11566 separator.lastIndex = 0;
11567 while ((match = separator.exec(substring))) {
11568 newEnd = match.index;
11569 }
11570 result = result.slice(0, newEnd == null ? end : newEnd);
11571 }
11572 } else if (string.indexOf(separator, end) != end) {
11573 var index = result.lastIndexOf(separator);
11574 if (index > -1) {
11575 result = result.slice(0, index);
11576 }
11577 }
11578 return result + omission;
11579 }
11580
11581 /**
11582 * The inverse of `_.escape`; this method converts the HTML entities
11583 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their
11584 * corresponding characters.
11585 *
11586 * **Note:** No other HTML entities are unescaped. To unescape additional HTML
11587 * entities use a third-party library like [_he_](https://mths.be/he).
11588 *
11589 * @static
11590 * @memberOf _
11591 * @category String
11592 * @param {string} [string=''] The string to unescape.
11593 * @returns {string} Returns the unescaped string.
11594 * @example
11595 *
11596 * _.unescape('fred, barney, &amp; pebbles');
11597 * // => 'fred, barney, & pebbles'
11598 */
11599 function unescape(string) {
11600 string = baseToString(string);
11601 return (string && reHasEscapedHtml.test(string))
11602 ? string.replace(reEscapedHtml, unescapeHtmlChar)
11603 : string;
11604 }
11605
11606 /**
11607 * Splits `string` into an array of its words.
11608 *
11609 * @static
11610 * @memberOf _
11611 * @category String
11612 * @param {string} [string=''] The string to inspect.
11613 * @param {RegExp|string} [pattern] The pattern to match words.
11614 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11615 * @returns {Array} Returns the words of `string`.
11616 * @example
11617 *
11618 * _.words('fred, barney, & pebbles');
11619 * // => ['fred', 'barney', 'pebbles']
11620 *
11621 * _.words('fred, barney, & pebbles', /[^, ]+/g);
11622 * // => ['fred', 'barney', '&', 'pebbles']
11623 */
11624 function words(string, pattern, guard) {
11625 if (guard && isIterateeCall(string, pattern, guard)) {
11626 pattern = undefined;
11627 }
11628 string = baseToString(string);
11629 return string.match(pattern || reWords) || [];
11630 }
11631
11632 /*------------------------------------------------------------------------*/
11633
11634 /**
11635 * Attempts to invoke `func`, returning either the result or the caught error
11636 * object. Any additional arguments are provided to `func` when it is invoked.
11637 *
11638 * @static
11639 * @memberOf _
11640 * @category Utility
11641 * @param {Function} func The function to attempt.
11642 * @returns {*} Returns the `func` result or error object.
11643 * @example
11644 *
11645 * // avoid throwing errors for invalid selectors
11646 * var elements = _.attempt(function(selector) {
11647 * return document.querySelectorAll(selector);
11648 * }, '>_>');
11649 *
11650 * if (_.isError(elements)) {
11651 * elements = [];
11652 * }
11653 */
11654 var attempt = restParam(function(func, args) {
11655 try {
11656 return func.apply(undefined, args);
11657 } catch(e) {
11658 return isError(e) ? e : new Error(e);
11659 }
11660 });
11661
11662 /**
11663 * Creates a function that invokes `func` with the `this` binding of `thisArg`
11664 * and arguments of the created function. If `func` is a property name the
11665 * created callback returns the property value for a given element. If `func`
11666 * is an object the created callback returns `true` for elements that contain
11667 * the equivalent object properties, otherwise it returns `false`.
11668 *
11669 * @static
11670 * @memberOf _
11671 * @alias iteratee
11672 * @category Utility
11673 * @param {*} [func=_.identity] The value to convert to a callback.
11674 * @param {*} [thisArg] The `this` binding of `func`.
11675 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11676 * @returns {Function} Returns the callback.
11677 * @example
11678 *
11679 * var users = [
11680 * { 'user': 'barney', 'age': 36 },
11681 * { 'user': 'fred', 'age': 40 }
11682 * ];
11683 *
11684 * // wrap to create custom callback shorthands
11685 * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
11686 * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
11687 * if (!match) {
11688 * return callback(func, thisArg);
11689 * }
11690 * return function(object) {
11691 * return match[2] == 'gt'
11692 * ? object[match[1]] > match[3]
11693 * : object[match[1]] < match[3];
11694 * };
11695 * });
11696 *
11697 * _.filter(users, 'age__gt36');
11698 * // => [{ 'user': 'fred', 'age': 40 }]
11699 */
11700 function callback(func, thisArg, guard) {
11701 if (guard && isIterateeCall(func, thisArg, guard)) {
11702 thisArg = undefined;
11703 }
11704 return isObjectLike(func)
11705 ? matches(func)
11706 : baseCallback(func, thisArg);
11707 }
11708
11709 /**
11710 * Creates a function that returns `value`.
11711 *
11712 * @static
11713 * @memberOf _
11714 * @category Utility
11715 * @param {*} value The value to return from the new function.
11716 * @returns {Function} Returns the new function.
11717 * @example
11718 *
11719 * var object = { 'user': 'fred' };
11720 * var getter = _.constant(object);
11721 *
11722 * getter() === object;
11723 * // => true
11724 */
11725 function constant(value) {
11726 return function() {
11727 return value;
11728 };
11729 }
11730
11731 /**
11732 * This method returns the first argument provided to it.
11733 *
11734 * @static
11735 * @memberOf _
11736 * @category Utility
11737 * @param {*} value Any value.
11738 * @returns {*} Returns `value`.
11739 * @example
11740 *
11741 * var object = { 'user': 'fred' };
11742 *
11743 * _.identity(object) === object;
11744 * // => true
11745 */
11746 function identity(value) {
11747 return value;
11748 }
11749
11750 /**
11751 * Creates a function that performs a deep comparison between a given object
11752 * and `source`, returning `true` if the given object has equivalent property
11753 * values, else `false`.
11754 *
11755 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
11756 * numbers, `Object` objects, regexes, and strings. Objects are compared by
11757 * their own, not inherited, enumerable properties. For comparing a single
11758 * own or inherited property value see `_.matchesProperty`.
11759 *
11760 * @static
11761 * @memberOf _
11762 * @category Utility
11763 * @param {Object} source The object of property values to match.
11764 * @returns {Function} Returns the new function.
11765 * @example
11766 *
11767 * var users = [
11768 * { 'user': 'barney', 'age': 36, 'active': true },
11769 * { 'user': 'fred', 'age': 40, 'active': false }
11770 * ];
11771 *
11772 * _.filter(users, _.matches({ 'age': 40, 'active': false }));
11773 * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
11774 */
11775 function matches(source) {
11776 return baseMatches(baseClone(source, true));
11777 }
11778
11779 /**
11780 * Creates a function that compares the property value of `path` on a given
11781 * object to `value`.
11782 *
11783 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
11784 * numbers, `Object` objects, regexes, and strings. Objects are compared by
11785 * their own, not inherited, enumerable properties.
11786 *
11787 * @static
11788 * @memberOf _
11789 * @category Utility
11790 * @param {Array|string} path The path of the property to get.
11791 * @param {*} srcValue The value to match.
11792 * @returns {Function} Returns the new function.
11793 * @example
11794 *
11795 * var users = [
11796 * { 'user': 'barney' },
11797 * { 'user': 'fred' }
11798 * ];
11799 *
11800 * _.find(users, _.matchesProperty('user', 'fred'));
11801 * // => { 'user': 'fred' }
11802 */
11803 function matchesProperty(path, srcValue) {
11804 return baseMatchesProperty(path, baseClone(srcValue, true));
11805 }
11806
11807 /**
11808 * Creates a function that invokes the method at `path` on a given object.
11809 * Any additional arguments are provided to the invoked method.
11810 *
11811 * @static
11812 * @memberOf _
11813 * @category Utility
11814 * @param {Array|string} path The path of the method to invoke.
11815 * @param {...*} [args] The arguments to invoke the method with.
11816 * @returns {Function} Returns the new function.
11817 * @example
11818 *
11819 * var objects = [
11820 * { 'a': { 'b': { 'c': _.constant(2) } } },
11821 * { 'a': { 'b': { 'c': _.constant(1) } } }
11822 * ];
11823 *
11824 * _.map(objects, _.method('a.b.c'));
11825 * // => [2, 1]
11826 *
11827 * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
11828 * // => [1, 2]
11829 */
11830 var method = restParam(function(path, args) {
11831 return function(object) {
11832 return invokePath(object, path, args);
11833 };
11834 });
11835
11836 /**
11837 * The opposite of `_.method`; this method creates a function that invokes
11838 * the method at a given path on `object`. Any additional arguments are
11839 * provided to the invoked method.
11840 *
11841 * @static
11842 * @memberOf _
11843 * @category Utility
11844 * @param {Object} object The object to query.
11845 * @param {...*} [args] The arguments to invoke the method with.
11846 * @returns {Function} Returns the new function.
11847 * @example
11848 *
11849 * var array = _.times(3, _.constant),
11850 * object = { 'a': array, 'b': array, 'c': array };
11851 *
11852 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
11853 * // => [2, 0]
11854 *
11855 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
11856 * // => [2, 0]
11857 */
11858 var methodOf = restParam(function(object, args) {
11859 return function(path) {
11860 return invokePath(object, path, args);
11861 };
11862 });
11863
11864 /**
11865 * Adds all own enumerable function properties of a source object to the
11866 * destination object. If `object` is a function then methods are added to
11867 * its prototype as well.
11868 *
11869 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
11870 * avoid conflicts caused by modifying the original.
11871 *
11872 * @static
11873 * @memberOf _
11874 * @category Utility
11875 * @param {Function|Object} [object=lodash] The destination object.
11876 * @param {Object} source The object of functions to add.
11877 * @param {Object} [options] The options object.
11878 * @param {boolean} [options.chain=true] Specify whether the functions added
11879 * are chainable.
11880 * @returns {Function|Object} Returns `object`.
11881 * @example
11882 *
11883 * function vowels(string) {
11884 * return _.filter(string, function(v) {
11885 * return /[aeiou]/i.test(v);
11886 * });
11887 * }
11888 *
11889 * _.mixin({ 'vowels': vowels });
11890 * _.vowels('fred');
11891 * // => ['e']
11892 *
11893 * _('fred').vowels().value();
11894 * // => ['e']
11895 *
11896 * _.mixin({ 'vowels': vowels }, { 'chain': false });
11897 * _('fred').vowels();
11898 * // => ['e']
11899 */
11900 function mixin(object, source, options) {
11901 if (options == null) {
11902 var isObj = isObject(source),
11903 props = isObj ? keys(source) : undefined,
11904 methodNames = (props && props.length) ? baseFunctions(source, props) : undefined;
11905
11906 if (!(methodNames ? methodNames.length : isObj)) {
11907 methodNames = false;
11908 options = source;
11909 source = object;
11910 object = this;
11911 }
11912 }
11913 if (!methodNames) {
11914 methodNames = baseFunctions(source, keys(source));
11915 }
11916 var chain = true,
11917 index = -1,
11918 isFunc = isFunction(object),
11919 length = methodNames.length;
11920
11921 if (options === false) {
11922 chain = false;
11923 } else if (isObject(options) && 'chain' in options) {
11924 chain = options.chain;
11925 }
11926 while (++index < length) {
11927 var methodName = methodNames[index],
11928 func = source[methodName];
11929
11930 object[methodName] = func;
11931 if (isFunc) {
11932 object.prototype[methodName] = (function(func) {
11933 return function() {
11934 var chainAll = this.__chain__;
11935 if (chain || chainAll) {
11936 var result = object(this.__wrapped__),
11937 actions = result.__actions__ = arrayCopy(this.__actions__);
11938
11939 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
11940 result.__chain__ = chainAll;
11941 return result;
11942 }
11943 return func.apply(object, arrayPush([this.value()], arguments));
11944 };
11945 }(func));
11946 }
11947 }
11948 return object;
11949 }
11950
11951 /**
11952 * Reverts the `_` variable to its previous value and returns a reference to
11953 * the `lodash` function.
11954 *
11955 * @static
11956 * @memberOf _
11957 * @category Utility
11958 * @returns {Function} Returns the `lodash` function.
11959 * @example
11960 *
11961 * var lodash = _.noConflict();
11962 */
11963 function noConflict() {
11964 root._ = oldDash;
11965 return this;
11966 }
11967
11968 /**
11969 * A no-operation function that returns `undefined` regardless of the
11970 * arguments it receives.
11971 *
11972 * @static
11973 * @memberOf _
11974 * @category Utility
11975 * @example
11976 *
11977 * var object = { 'user': 'fred' };
11978 *
11979 * _.noop(object) === undefined;
11980 * // => true
11981 */
11982 function noop() {
11983 // No operation performed.
11984 }
11985
11986 /**
11987 * Creates a function that returns the property value at `path` on a
11988 * given object.
11989 *
11990 * @static
11991 * @memberOf _
11992 * @category Utility
11993 * @param {Array|string} path The path of the property to get.
11994 * @returns {Function} Returns the new function.
11995 * @example
11996 *
11997 * var objects = [
11998 * { 'a': { 'b': { 'c': 2 } } },
11999 * { 'a': { 'b': { 'c': 1 } } }
12000 * ];
12001 *
12002 * _.map(objects, _.property('a.b.c'));
12003 * // => [2, 1]
12004 *
12005 * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
12006 * // => [1, 2]
12007 */
12008 function property(path) {
12009 return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
12010 }
12011
12012 /**
12013 * The opposite of `_.property`; this method creates a function that returns
12014 * the property value at a given path on `object`.
12015 *
12016 * @static
12017 * @memberOf _
12018 * @category Utility
12019 * @param {Object} object The object to query.
12020 * @returns {Function} Returns the new function.
12021 * @example
12022 *
12023 * var array = [0, 1, 2],
12024 * object = { 'a': array, 'b': array, 'c': array };
12025 *
12026 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
12027 * // => [2, 0]
12028 *
12029 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
12030 * // => [2, 0]
12031 */
12032 function propertyOf(object) {
12033 return function(path) {
12034 return baseGet(object, toPath(path), path + '');
12035 };
12036 }
12037
12038 /**
12039 * Creates an array of numbers (positive and/or negative) progressing from
12040 * `start` up to, but not including, `end`. If `end` is not specified it is
12041 * set to `start` with `start` then set to `0`. If `end` is less than `start`
12042 * a zero-length range is created unless a negative `step` is specified.
12043 *
12044 * @static
12045 * @memberOf _
12046 * @category Utility
12047 * @param {number} [start=0] The start of the range.
12048 * @param {number} end The end of the range.
12049 * @param {number} [step=1] The value to increment or decrement by.
12050 * @returns {Array} Returns the new array of numbers.
12051 * @example
12052 *
12053 * _.range(4);
12054 * // => [0, 1, 2, 3]
12055 *
12056 * _.range(1, 5);
12057 * // => [1, 2, 3, 4]
12058 *
12059 * _.range(0, 20, 5);
12060 * // => [0, 5, 10, 15]
12061 *
12062 * _.range(0, -4, -1);
12063 * // => [0, -1, -2, -3]
12064 *
12065 * _.range(1, 4, 0);
12066 * // => [1, 1, 1]
12067 *
12068 * _.range(0);
12069 * // => []
12070 */
12071 function range(start, end, step) {
12072 if (step && isIterateeCall(start, end, step)) {
12073 end = step = undefined;
12074 }
12075 start = +start || 0;
12076 step = step == null ? 1 : (+step || 0);
12077
12078 if (end == null) {
12079 end = start;
12080 start = 0;
12081 } else {
12082 end = +end || 0;
12083 }
12084 // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
12085 // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
12086 var index = -1,
12087 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
12088 result = Array(length);
12089
12090 while (++index < length) {
12091 result[index] = start;
12092 start += step;
12093 }
12094 return result;
12095 }
12096
12097 /**
12098 * Invokes the iteratee function `n` times, returning an array of the results
12099 * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
12100 * one argument; (index).
12101 *
12102 * @static
12103 * @memberOf _
12104 * @category Utility
12105 * @param {number} n The number of times to invoke `iteratee`.
12106 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
12107 * @param {*} [thisArg] The `this` binding of `iteratee`.
12108 * @returns {Array} Returns the array of results.
12109 * @example
12110 *
12111 * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
12112 * // => [3, 6, 4]
12113 *
12114 * _.times(3, function(n) {
12115 * mage.castSpell(n);
12116 * });
12117 * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
12118 *
12119 * _.times(3, function(n) {
12120 * this.cast(n);
12121 * }, mage);
12122 * // => also invokes `mage.castSpell(n)` three times
12123 */
12124 function times(n, iteratee, thisArg) {
12125 n = nativeFloor(n);
12126
12127 // Exit early to avoid a JSC JIT bug in Safari 8
12128 // where `Array(0)` is treated as `Array(1)`.
12129 if (n < 1 || !nativeIsFinite(n)) {
12130 return [];
12131 }
12132 var index = -1,
12133 result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
12134
12135 iteratee = bindCallback(iteratee, thisArg, 1);
12136 while (++index < n) {
12137 if (index < MAX_ARRAY_LENGTH) {
12138 result[index] = iteratee(index);
12139 } else {
12140 iteratee(index);
12141 }
12142 }
12143 return result;
12144 }
12145
12146 /**
12147 * Generates a unique ID. If `prefix` is provided the ID is appended to it.
12148 *
12149 * @static
12150 * @memberOf _
12151 * @category Utility
12152 * @param {string} [prefix] The value to prefix the ID with.
12153 * @returns {string} Returns the unique ID.
12154 * @example
12155 *
12156 * _.uniqueId('contact_');
12157 * // => 'contact_104'
12158 *
12159 * _.uniqueId();
12160 * // => '105'
12161 */
12162 function uniqueId(prefix) {
12163 var id = ++idCounter;
12164 return baseToString(prefix) + id;
12165 }
12166
12167 /*------------------------------------------------------------------------*/
12168
12169 /**
12170 * Adds two numbers.
12171 *
12172 * @static
12173 * @memberOf _
12174 * @category Math
12175 * @param {number} augend The first number to add.
12176 * @param {number} addend The second number to add.
12177 * @returns {number} Returns the sum.
12178 * @example
12179 *
12180 * _.add(6, 4);
12181 * // => 10
12182 */
12183 function add(augend, addend) {
12184 return (+augend || 0) + (+addend || 0);
12185 }
12186
12187 /**
12188 * Calculates `n` rounded up to `precision`.
12189 *
12190 * @static
12191 * @memberOf _
12192 * @category Math
12193 * @param {number} n The number to round up.
12194 * @param {number} [precision=0] The precision to round up to.
12195 * @returns {number} Returns the rounded up number.
12196 * @example
12197 *
12198 * _.ceil(4.006);
12199 * // => 5
12200 *
12201 * _.ceil(6.004, 2);
12202 * // => 6.01
12203 *
12204 * _.ceil(6040, -2);
12205 * // => 6100
12206 */
12207 var ceil = createRound('ceil');
12208
12209 /**
12210 * Calculates `n` rounded down to `precision`.
12211 *
12212 * @static
12213 * @memberOf _
12214 * @category Math
12215 * @param {number} n The number to round down.
12216 * @param {number} [precision=0] The precision to round down to.
12217 * @returns {number} Returns the rounded down number.
12218 * @example
12219 *
12220 * _.floor(4.006);
12221 * // => 4
12222 *
12223 * _.floor(0.046, 2);
12224 * // => 0.04
12225 *
12226 * _.floor(4060, -2);
12227 * // => 4000
12228 */
12229 var floor = createRound('floor');
12230
12231 /**
12232 * Gets the maximum value of `collection`. If `collection` is empty or falsey
12233 * `-Infinity` is returned. If an iteratee function is provided it is invoked
12234 * for each value in `collection` to generate the criterion by which the value
12235 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
12236 * arguments: (value, index, collection).
12237 *
12238 * If a property name is provided for `iteratee` the created `_.property`
12239 * style callback returns the property value of the given element.
12240 *
12241 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12242 * style callback returns `true` for elements that have a matching property
12243 * value, else `false`.
12244 *
12245 * If an object is provided for `iteratee` the created `_.matches` style
12246 * callback returns `true` for elements that have the properties of the given
12247 * object, else `false`.
12248 *
12249 * @static
12250 * @memberOf _
12251 * @category Math
12252 * @param {Array|Object|string} collection The collection to iterate over.
12253 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
12254 * @param {*} [thisArg] The `this` binding of `iteratee`.
12255 * @returns {*} Returns the maximum value.
12256 * @example
12257 *
12258 * _.max([4, 2, 8, 6]);
12259 * // => 8
12260 *
12261 * _.max([]);
12262 * // => -Infinity
12263 *
12264 * var users = [
12265 * { 'user': 'barney', 'age': 36 },
12266 * { 'user': 'fred', 'age': 40 }
12267 * ];
12268 *
12269 * _.max(users, function(chr) {
12270 * return chr.age;
12271 * });
12272 * // => { 'user': 'fred', 'age': 40 }
12273 *
12274 * // using the `_.property` callback shorthand
12275 * _.max(users, 'age');
12276 * // => { 'user': 'fred', 'age': 40 }
12277 */
12278 var max = createExtremum(gt, NEGATIVE_INFINITY);
12279
12280 /**
12281 * Gets the minimum value of `collection`. If `collection` is empty or falsey
12282 * `Infinity` is returned. If an iteratee function is provided it is invoked
12283 * for each value in `collection` to generate the criterion by which the value
12284 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
12285 * arguments: (value, index, collection).
12286 *
12287 * If a property name is provided for `iteratee` the created `_.property`
12288 * style callback returns the property value of the given element.
12289 *
12290 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12291 * style callback returns `true` for elements that have a matching property
12292 * value, else `false`.
12293 *
12294 * If an object is provided for `iteratee` the created `_.matches` style
12295 * callback returns `true` for elements that have the properties of the given
12296 * object, else `false`.
12297 *
12298 * @static
12299 * @memberOf _
12300 * @category Math
12301 * @param {Array|Object|string} collection The collection to iterate over.
12302 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
12303 * @param {*} [thisArg] The `this` binding of `iteratee`.
12304 * @returns {*} Returns the minimum value.
12305 * @example
12306 *
12307 * _.min([4, 2, 8, 6]);
12308 * // => 2
12309 *
12310 * _.min([]);
12311 * // => Infinity
12312 *
12313 * var users = [
12314 * { 'user': 'barney', 'age': 36 },
12315 * { 'user': 'fred', 'age': 40 }
12316 * ];
12317 *
12318 * _.min(users, function(chr) {
12319 * return chr.age;
12320 * });
12321 * // => { 'user': 'barney', 'age': 36 }
12322 *
12323 * // using the `_.property` callback shorthand
12324 * _.min(users, 'age');
12325 * // => { 'user': 'barney', 'age': 36 }
12326 */
12327 var min = createExtremum(lt, POSITIVE_INFINITY);
12328
12329 /**
12330 * Calculates `n` rounded to `precision`.
12331 *
12332 * @static
12333 * @memberOf _
12334 * @category Math
12335 * @param {number} n The number to round.
12336 * @param {number} [precision=0] The precision to round to.
12337 * @returns {number} Returns the rounded number.
12338 * @example
12339 *
12340 * _.round(4.006);
12341 * // => 4
12342 *
12343 * _.round(4.006, 2);
12344 * // => 4.01
12345 *
12346 * _.round(4060, -2);
12347 * // => 4100
12348 */
12349 var round = createRound('round');
12350
12351 /**
12352 * Gets the sum of the values in `collection`.
12353 *
12354 * @static
12355 * @memberOf _
12356 * @category Math
12357 * @param {Array|Object|string} collection The collection to iterate over.
12358 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
12359 * @param {*} [thisArg] The `this` binding of `iteratee`.
12360 * @returns {number} Returns the sum.
12361 * @example
12362 *
12363 * _.sum([4, 6]);
12364 * // => 10
12365 *
12366 * _.sum({ 'a': 4, 'b': 6 });
12367 * // => 10
12368 *
12369 * var objects = [
12370 * { 'n': 4 },
12371 * { 'n': 6 }
12372 * ];
12373 *
12374 * _.sum(objects, function(object) {
12375 * return object.n;
12376 * });
12377 * // => 10
12378 *
12379 * // using the `_.property` callback shorthand
12380 * _.sum(objects, 'n');
12381 * // => 10
12382 */
12383 function sum(collection, iteratee, thisArg) {
12384 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
12385 iteratee = undefined;
12386 }
12387 iteratee = getCallback(iteratee, thisArg, 3);
12388 return iteratee.length == 1
12389 ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
12390 : baseSum(collection, iteratee);
12391 }
12392
12393 /*------------------------------------------------------------------------*/
12394
12395 // Ensure wrappers are instances of `baseLodash`.
12396 lodash.prototype = baseLodash.prototype;
12397
12398 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
12399 LodashWrapper.prototype.constructor = LodashWrapper;
12400
12401 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
12402 LazyWrapper.prototype.constructor = LazyWrapper;
12403
12404 // Add functions to the `Map` cache.
12405 MapCache.prototype['delete'] = mapDelete;
12406 MapCache.prototype.get = mapGet;
12407 MapCache.prototype.has = mapHas;
12408 MapCache.prototype.set = mapSet;
12409
12410 // Add functions to the `Set` cache.
12411 SetCache.prototype.push = cachePush;
12412
12413 // Assign cache to `_.memoize`.
12414 memoize.Cache = MapCache;
12415
12416 // Add functions that return wrapped values when chaining.
12417 lodash.after = after;
12418 lodash.ary = ary;
12419 lodash.assign = assign;
12420 lodash.at = at;
12421 lodash.before = before;
12422 lodash.bind = bind;
12423 lodash.bindAll = bindAll;
12424 lodash.bindKey = bindKey;
12425 lodash.callback = callback;
12426 lodash.chain = chain;
12427 lodash.chunk = chunk;
12428 lodash.compact = compact;
12429 lodash.constant = constant;
12430 lodash.countBy = countBy;
12431 lodash.create = create;
12432 lodash.curry = curry;
12433 lodash.curryRight = curryRight;
12434 lodash.debounce = debounce;
12435 lodash.defaults = defaults;
12436 lodash.defaultsDeep = defaultsDeep;
12437 lodash.defer = defer;
12438 lodash.delay = delay;
12439 lodash.difference = difference;
12440 lodash.drop = drop;
12441 lodash.dropRight = dropRight;
12442 lodash.dropRightWhile = dropRightWhile;
12443 lodash.dropWhile = dropWhile;
12444 lodash.fill = fill;
12445 lodash.filter = filter;
12446 lodash.flatten = flatten;
12447 lodash.flattenDeep = flattenDeep;
12448 lodash.flow = flow;
12449 lodash.flowRight = flowRight;
12450 lodash.forEach = forEach;
12451 lodash.forEachRight = forEachRight;
12452 lodash.forIn = forIn;
12453 lodash.forInRight = forInRight;
12454 lodash.forOwn = forOwn;
12455 lodash.forOwnRight = forOwnRight;
12456 lodash.functions = functions;
12457 lodash.groupBy = groupBy;
12458 lodash.indexBy = indexBy;
12459 lodash.initial = initial;
12460 lodash.intersection = intersection;
12461 lodash.invert = invert;
12462 lodash.invoke = invoke;
12463 lodash.keys = keys;
12464 lodash.keysIn = keysIn;
12465 lodash.map = map;
12466 lodash.mapKeys = mapKeys;
12467 lodash.mapValues = mapValues;
12468 lodash.matches = matches;
12469 lodash.matchesProperty = matchesProperty;
12470 lodash.memoize = memoize;
12471 lodash.merge = merge;
12472 lodash.method = method;
12473 lodash.methodOf = methodOf;
12474 lodash.mixin = mixin;
12475 lodash.modArgs = modArgs;
12476 lodash.negate = negate;
12477 lodash.omit = omit;
12478 lodash.once = once;
12479 lodash.pairs = pairs;
12480 lodash.partial = partial;
12481 lodash.partialRight = partialRight;
12482 lodash.partition = partition;
12483 lodash.pick = pick;
12484 lodash.pluck = pluck;
12485 lodash.property = property;
12486 lodash.propertyOf = propertyOf;
12487 lodash.pull = pull;
12488 lodash.pullAt = pullAt;
12489 lodash.range = range;
12490 lodash.rearg = rearg;
12491 lodash.reject = reject;
12492 lodash.remove = remove;
12493 lodash.rest = rest;
12494 lodash.restParam = restParam;
12495 lodash.set = set;
12496 lodash.shuffle = shuffle;
12497 lodash.slice = slice;
12498 lodash.sortBy = sortBy;
12499 lodash.sortByAll = sortByAll;
12500 lodash.sortByOrder = sortByOrder;
12501 lodash.spread = spread;
12502 lodash.take = take;
12503 lodash.takeRight = takeRight;
12504 lodash.takeRightWhile = takeRightWhile;
12505 lodash.takeWhile = takeWhile;
12506 lodash.tap = tap;
12507 lodash.throttle = throttle;
12508 lodash.thru = thru;
12509 lodash.times = times;
12510 lodash.toArray = toArray;
12511 lodash.toPlainObject = toPlainObject;
12512 lodash.transform = transform;
12513 lodash.union = union;
12514 lodash.uniq = uniq;
12515 lodash.unzip = unzip;
12516 lodash.unzipWith = unzipWith;
12517 lodash.values = values;
12518 lodash.valuesIn = valuesIn;
12519 lodash.where = where;
12520 lodash.without = without;
12521 lodash.wrap = wrap;
12522 lodash.xor = xor;
12523 lodash.zip = zip;
12524 lodash.zipObject = zipObject;
12525 lodash.zipWith = zipWith;
12526
12527 // Add aliases.
12528 lodash.backflow = flowRight;
12529 lodash.collect = map;
12530 lodash.compose = flowRight;
12531 lodash.each = forEach;
12532 lodash.eachRight = forEachRight;
12533 lodash.extend = assign;
12534 lodash.iteratee = callback;
12535 lodash.methods = functions;
12536 lodash.object = zipObject;
12537 lodash.select = filter;
12538 lodash.tail = rest;
12539 lodash.unique = uniq;
12540
12541 // Add functions to `lodash.prototype`.
12542 mixin(lodash, lodash);
12543
12544 /*------------------------------------------------------------------------*/
12545
12546 // Add functions that return unwrapped values when chaining.
12547 lodash.add = add;
12548 lodash.attempt = attempt;
12549 lodash.camelCase = camelCase;
12550 lodash.capitalize = capitalize;
12551 lodash.ceil = ceil;
12552 lodash.clone = clone;
12553 lodash.cloneDeep = cloneDeep;
12554 lodash.deburr = deburr;
12555 lodash.endsWith = endsWith;
12556 lodash.escape = escape;
12557 lodash.escapeRegExp = escapeRegExp;
12558 lodash.every = every;
12559 lodash.find = find;
12560 lodash.findIndex = findIndex;
12561 lodash.findKey = findKey;
12562 lodash.findLast = findLast;
12563 lodash.findLastIndex = findLastIndex;
12564 lodash.findLastKey = findLastKey;
12565 lodash.findWhere = findWhere;
12566 lodash.first = first;
12567 lodash.floor = floor;
12568 lodash.get = get;
12569 lodash.gt = gt;
12570 lodash.gte = gte;
12571 lodash.has = has;
12572 lodash.identity = identity;
12573 lodash.includes = includes;
12574 lodash.indexOf = indexOf;
12575 lodash.inRange = inRange;
12576 lodash.isArguments = isArguments;
12577 lodash.isArray = isArray;
12578 lodash.isBoolean = isBoolean;
12579 lodash.isDate = isDate;
12580 lodash.isElement = isElement;
12581 lodash.isEmpty = isEmpty;
12582 lodash.isEqual = isEqual;
12583 lodash.isError = isError;
12584 lodash.isFinite = isFinite;
12585 lodash.isFunction = isFunction;
12586 lodash.isMatch = isMatch;
12587 lodash.isNaN = isNaN;
12588 lodash.isNative = isNative;
12589 lodash.isNull = isNull;
12590 lodash.isNumber = isNumber;
12591 lodash.isObject = isObject;
12592 lodash.isPlainObject = isPlainObject;
12593 lodash.isRegExp = isRegExp;
12594 lodash.isString = isString;
12595 lodash.isTypedArray = isTypedArray;
12596 lodash.isUndefined = isUndefined;
12597 lodash.kebabCase = kebabCase;
12598 lodash.last = last;
12599 lodash.lastIndexOf = lastIndexOf;
12600 lodash.lt = lt;
12601 lodash.lte = lte;
12602 lodash.max = max;
12603 lodash.min = min;
12604 lodash.noConflict = noConflict;
12605 lodash.noop = noop;
12606 lodash.now = now;
12607 lodash.pad = pad;
12608 lodash.padLeft = padLeft;
12609 lodash.padRight = padRight;
12610 lodash.parseInt = parseInt;
12611 lodash.random = random;
12612 lodash.reduce = reduce;
12613 lodash.reduceRight = reduceRight;
12614 lodash.repeat = repeat;
12615 lodash.result = result;
12616 lodash.round = round;
12617 lodash.runInContext = runInContext;
12618 lodash.size = size;
12619 lodash.snakeCase = snakeCase;
12620 lodash.some = some;
12621 lodash.sortedIndex = sortedIndex;
12622 lodash.sortedLastIndex = sortedLastIndex;
12623 lodash.startCase = startCase;
12624 lodash.startsWith = startsWith;
12625 lodash.sum = sum;
12626 lodash.template = template;
12627 lodash.trim = trim;
12628 lodash.trimLeft = trimLeft;
12629 lodash.trimRight = trimRight;
12630 lodash.trunc = trunc;
12631 lodash.unescape = unescape;
12632 lodash.uniqueId = uniqueId;
12633 lodash.words = words;
12634
12635 // Add aliases.
12636 lodash.all = every;
12637 lodash.any = some;
12638 lodash.contains = includes;
12639 lodash.eq = isEqual;
12640 lodash.detect = find;
12641 lodash.foldl = reduce;
12642 lodash.foldr = reduceRight;
12643 lodash.head = first;
12644 lodash.include = includes;
12645 lodash.inject = reduce;
12646
12647 mixin(lodash, (function() {
12648 var source = {};
12649 baseForOwn(lodash, function(func, methodName) {
12650 if (!lodash.prototype[methodName]) {
12651 source[methodName] = func;
12652 }
12653 });
12654 return source;
12655 }()), false);
12656
12657 /*------------------------------------------------------------------------*/
12658
12659 // Add functions capable of returning wrapped and unwrapped values when chaining.
12660 lodash.sample = sample;
12661
12662 lodash.prototype.sample = function(n) {
12663 if (!this.__chain__ && n == null) {
12664 return sample(this.value());
12665 }
12666 return this.thru(function(value) {
12667 return sample(value, n);
12668 });
12669 };
12670
12671 /*------------------------------------------------------------------------*/
12672
12673 /**
12674 * The semantic version number.
12675 *
12676 * @static
12677 * @memberOf _
12678 * @type string
12679 */
12680 lodash.VERSION = VERSION;
12681
12682 // Assign default placeholders.
12683 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
12684 lodash[methodName].placeholder = lodash;
12685 });
12686
12687 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
12688 arrayEach(['drop', 'take'], function(methodName, index) {
12689 LazyWrapper.prototype[methodName] = function(n) {
12690 var filtered = this.__filtered__;
12691 if (filtered && !index) {
12692 return new LazyWrapper(this);
12693 }
12694 n = n == null ? 1 : nativeMax(nativeFloor(n) || 0, 0);
12695
12696 var result = this.clone();
12697 if (filtered) {
12698 result.__takeCount__ = nativeMin(result.__takeCount__, n);
12699 } else {
12700 result.__views__.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
12701 }
12702 return result;
12703 };
12704
12705 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
12706 return this.reverse()[methodName](n).reverse();
12707 };
12708 });
12709
12710 // Add `LazyWrapper` methods that accept an `iteratee` value.
12711 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
12712 var type = index + 1,
12713 isFilter = type != LAZY_MAP_FLAG;
12714
12715 LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
12716 var result = this.clone();
12717 result.__iteratees__.push({ 'iteratee': getCallback(iteratee, thisArg, 1), 'type': type });
12718 result.__filtered__ = result.__filtered__ || isFilter;
12719 return result;
12720 };
12721 });
12722
12723 // Add `LazyWrapper` methods for `_.first` and `_.last`.
12724 arrayEach(['first', 'last'], function(methodName, index) {
12725 var takeName = 'take' + (index ? 'Right' : '');
12726
12727 LazyWrapper.prototype[methodName] = function() {
12728 return this[takeName](1).value()[0];
12729 };
12730 });
12731
12732 // Add `LazyWrapper` methods for `_.initial` and `_.rest`.
12733 arrayEach(['initial', 'rest'], function(methodName, index) {
12734 var dropName = 'drop' + (index ? '' : 'Right');
12735
12736 LazyWrapper.prototype[methodName] = function() {
12737 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
12738 };
12739 });
12740
12741 // Add `LazyWrapper` methods for `_.pluck` and `_.where`.
12742 arrayEach(['pluck', 'where'], function(methodName, index) {
12743 var operationName = index ? 'filter' : 'map',
12744 createCallback = index ? baseMatches : property;
12745
12746 LazyWrapper.prototype[methodName] = function(value) {
12747 return this[operationName](createCallback(value));
12748 };
12749 });
12750
12751 LazyWrapper.prototype.compact = function() {
12752 return this.filter(identity);
12753 };
12754
12755 LazyWrapper.prototype.reject = function(predicate, thisArg) {
12756 predicate = getCallback(predicate, thisArg, 1);
12757 return this.filter(function(value) {
12758 return !predicate(value);
12759 });
12760 };
12761
12762 LazyWrapper.prototype.slice = function(start, end) {
12763 start = start == null ? 0 : (+start || 0);
12764
12765 var result = this;
12766 if (result.__filtered__ && (start > 0 || end < 0)) {
12767 return new LazyWrapper(result);
12768 }
12769 if (start < 0) {
12770 result = result.takeRight(-start);
12771 } else if (start) {
12772 result = result.drop(start);
12773 }
12774 if (end !== undefined) {
12775 end = (+end || 0);
12776 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
12777 }
12778 return result;
12779 };
12780
12781 LazyWrapper.prototype.takeRightWhile = function(predicate, thisArg) {
12782 return this.reverse().takeWhile(predicate, thisArg).reverse();
12783 };
12784
12785 LazyWrapper.prototype.toArray = function() {
12786 return this.take(POSITIVE_INFINITY);
12787 };
12788
12789 // Add `LazyWrapper` methods to `lodash.prototype`.
12790 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
12791 var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
12792 retUnwrapped = /^(?:first|last)$/.test(methodName),
12793 lodashFunc = lodash[retUnwrapped ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName];
12794
12795 if (!lodashFunc) {
12796 return;
12797 }
12798 lodash.prototype[methodName] = function() {
12799 var args = retUnwrapped ? [1] : arguments,
12800 chainAll = this.__chain__,
12801 value = this.__wrapped__,
12802 isHybrid = !!this.__actions__.length,
12803 isLazy = value instanceof LazyWrapper,
12804 iteratee = args[0],
12805 useLazy = isLazy || isArray(value);
12806
12807 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
12808 // Avoid lazy use if the iteratee has a "length" value other than `1`.
12809 isLazy = useLazy = false;
12810 }
12811 var interceptor = function(value) {
12812 return (retUnwrapped && chainAll)
12813 ? lodashFunc(value, 1)[0]
12814 : lodashFunc.apply(undefined, arrayPush([value], args));
12815 };
12816
12817 var action = { 'func': thru, 'args': [interceptor], 'thisArg': undefined },
12818 onlyLazy = isLazy && !isHybrid;
12819
12820 if (retUnwrapped && !chainAll) {
12821 if (onlyLazy) {
12822 value = value.clone();
12823 value.__actions__.push(action);
12824 return func.call(value);
12825 }
12826 return lodashFunc.call(undefined, this.value())[0];
12827 }
12828 if (!retUnwrapped && useLazy) {
12829 value = onlyLazy ? value : new LazyWrapper(this);
12830 var result = func.apply(value, args);
12831 result.__actions__.push(action);
12832 return new LodashWrapper(result, chainAll);
12833 }
12834 return this.thru(interceptor);
12835 };
12836 });
12837
12838 // Add `Array` and `String` methods to `lodash.prototype`.
12839 arrayEach(['join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
12840 var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
12841 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
12842 retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
12843
12844 lodash.prototype[methodName] = function() {
12845 var args = arguments;
12846 if (retUnwrapped && !this.__chain__) {
12847 return func.apply(this.value(), args);
12848 }
12849 return this[chainName](function(value) {
12850 return func.apply(value, args);
12851 });
12852 };
12853 });
12854
12855 // Map minified function names to their real names.
12856 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
12857 var lodashFunc = lodash[methodName];
12858 if (lodashFunc) {
12859 var key = lodashFunc.name,
12860 names = realNames[key] || (realNames[key] = []);
12861
12862 names.push({ 'name': methodName, 'func': lodashFunc });
12863 }
12864 });
12865
12866 realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }];
12867
12868 // Add functions to the lazy wrapper.
12869 LazyWrapper.prototype.clone = lazyClone;
12870 LazyWrapper.prototype.reverse = lazyReverse;
12871 LazyWrapper.prototype.value = lazyValue;
12872
12873 // Add chaining functions to the `lodash` wrapper.
12874 lodash.prototype.chain = wrapperChain;
12875 lodash.prototype.commit = wrapperCommit;
12876 lodash.prototype.concat = wrapperConcat;
12877 lodash.prototype.plant = wrapperPlant;
12878 lodash.prototype.reverse = wrapperReverse;
12879 lodash.prototype.toString = wrapperToString;
12880 lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
12881
12882 // Add function aliases to the `lodash` wrapper.
12883 lodash.prototype.collect = lodash.prototype.map;
12884 lodash.prototype.head = lodash.prototype.first;
12885 lodash.prototype.select = lodash.prototype.filter;
12886 lodash.prototype.tail = lodash.prototype.rest;
12887
12888 return lodash;
12889 }
12890
12891 /*--------------------------------------------------------------------------*/
12892
12893 // Export lodash.
12894 var _ = runInContext();
12895
12896 // Some AMD build optimizers like r.js check for condition patterns like the following:
12897 if (true) {
12898 // Expose lodash to the global object when an AMD loader is present to avoid
12899 // errors in cases where lodash is loaded by a script tag and not intended
12900 // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
12901 // more details.
12902 root._ = _;
12903
12904 // Define as an anonymous module so, through path mapping, it can be
12905 // referenced as the "underscore" module.
12906 !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
12907 return _;
12908 }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
12909 }
12910 // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
12911 else if (freeExports && freeModule) {
12912 // Export for Node.js or RingoJS.
12913 if (moduleExports) {
12914 (freeModule.exports = _)._ = _;
12915 }
12916 // Export for Rhino with CommonJS support.
12917 else {
12918 freeExports._ = _;
12919 }
12920 }
12921 else {
12922 // Export for a browser or Rhino.
12923 root._ = _;
12924 }
12925 }.call(this));
12926
12927 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(12)(module), (function() { return this; }())))
12928
12929/***/ },
12930/* 10 */
12931/***/ function(module, exports, __webpack_require__) {
12932
12933 /* WEBPACK VAR INJECTION */(function(global) {(function checkMoreTypes(check) {
12934 'use strict';
12935
12936 /**
12937 Custom assertions and predicates for https://github.com/philbooth/check-types.js
12938 Created by Kensho https://github.com/kensho
12939 Copyright @ 2014 Kensho https://www.kensho.com/
12940 License: MIT
12941
12942 @module check
12943 */
12944
12945 if (!check) {
12946 if (false) {
12947 throw new Error('Cannot find check-types library, has it been loaded?');
12948 }
12949 check = __webpack_require__(13);
12950 }
12951
12952 /**
12953 Checks if argument is defined or not
12954
12955 This method now is part of the check-types.js
12956 @method defined
12957 */
12958 function defined(value) {
12959 return typeof value !== 'undefined';
12960 }
12961
12962 /**
12963 same as ===
12964
12965 @method same
12966 */
12967 function same(a, b) {
12968 return a === b;
12969 }
12970
12971 /**
12972 Returns true if the index is valid for give string / array
12973
12974 @method index
12975 */
12976 function index(list, k) {
12977 return defined(list) &&
12978 has(list, 'length') &&
12979 k >= 0 &&
12980 k < list.length;
12981 }
12982
12983 /**
12984 Returns true if both objects are the same type and have same length property
12985
12986 @method sameLength
12987 */
12988 function sameLength(a, b) {
12989 return typeof a === typeof b &&
12990 a && b &&
12991 a.length === b.length;
12992 }
12993
12994 /**
12995 Returns true if all items in an array are the same reference
12996
12997 @method allSame
12998 */
12999 function allSame(arr) {
13000 if (!check.array(arr)) {
13001 return false;
13002 }
13003 if (!arr.length) {
13004 return true;
13005 }
13006 var first = arr[0];
13007 return arr.every(function (item) {
13008 return item === first;
13009 });
13010 }
13011
13012 /**
13013 Returns true if given item is in the array
13014
13015 @method oneOf
13016 */
13017 function oneOf(arr, x) {
13018 check.verify.array(arr, 'expected an array');
13019 return arr.indexOf(x) !== -1;
13020 }
13021
13022 /**
13023 Returns true for urls of the format `git@....git`
13024
13025 @method git
13026 */
13027 function git(url) {
13028 return check.unemptyString(url) &&
13029 /^git@/.test(url);
13030 }
13031
13032 /**
13033 Checks if given value is 0 or 1
13034
13035 @method bit
13036 */
13037 function bit(value) {
13038 return value === 0 || value === 1;
13039 }
13040
13041 /**
13042 Checks if given value is true of false
13043
13044 @method bool
13045 */
13046 function bool(value) {
13047 return typeof value === 'boolean';
13048 }
13049
13050 /**
13051 Checks if given object has a property
13052 @method has
13053 */
13054 function has(o, property) {
13055 return Boolean(o && property &&
13056 typeof property === 'string' &&
13057 typeof o[property] !== 'undefined');
13058 }
13059
13060 /**
13061 Checks if given string is already in lower case
13062 @method lowerCase
13063 */
13064 function lowerCase(str) {
13065 return check.string(str) &&
13066 str.toLowerCase() === str;
13067 }
13068
13069 /**
13070 Returns true if the argument is an array with at least one value
13071 @method unemptyArray
13072 */
13073 function unemptyArray(a) {
13074 return check.array(a) && a.length > 0;
13075 }
13076
13077 /**
13078 Returns true if each item in the array passes the predicate
13079 @method arrayOf
13080 @param rule Predicate function
13081 @param a Array to check
13082 */
13083 function arrayOf(rule, a) {
13084 return check.array(a) && a.every(rule);
13085 }
13086
13087 /**
13088 Returns items from array that do not passes the predicate
13089 @method badItems
13090 @param rule Predicate function
13091 @param a Array with items
13092 */
13093 function badItems(rule, a) {
13094 check.verify.array(a, 'expected array to find bad items');
13095 return a.filter(notModifier(rule));
13096 }
13097
13098 /**
13099 Returns true if given array only has strings
13100 @method arrayOfStrings
13101 @param a Array to check
13102 @param checkLowerCase Checks if all strings are lowercase
13103 */
13104 function arrayOfStrings(a, checkLowerCase) {
13105 var v = check.array(a) && a.every(check.string);
13106 if (v && check.bool(checkLowerCase) && checkLowerCase) {
13107 return a.every(check.lowerCase);
13108 }
13109 return v;
13110 }
13111
13112 /**
13113 Returns true if given argument is array of arrays of strings
13114 @method arrayOfArraysOfStrings
13115 @param a Array to check
13116 @param checkLowerCase Checks if all strings are lowercase
13117 */
13118 function arrayOfArraysOfStrings(a, checkLowerCase) {
13119 return check.array(a) && a.every(function (arr) {
13120 return check.arrayOfStrings(arr, checkLowerCase);
13121 });
13122 }
13123
13124 /**
13125 Checks if object passes all rules in predicates.
13126
13127 check.all({ foo: 'foo' }, { foo: check.string }, 'wrong object');
13128
13129 This is a composition of check.every(check.map ...) calls
13130 https://github.com/philbooth/check-types.js#batch-operations
13131
13132 @method all
13133 @param {object} object object to check
13134 @param {object} predicates rules to check. Usually one per property.
13135 @public
13136 @returns true or false
13137 */
13138 function all(obj, predicates) {
13139 check.verify.object(obj, 'missing object to check');
13140 check.verify.object(predicates, 'missing predicates object');
13141 Object.keys(predicates).forEach(function (property) {
13142 check.verify.fn(predicates[property], 'not a predicate function for ' + property);
13143 });
13144 return check.every(check.map(obj, predicates));
13145 }
13146
13147 /**
13148 Checks given object against predicates object
13149 @method schema
13150 */
13151 function schema(predicates, obj) {
13152 return all(obj, predicates);
13153 }
13154
13155 /** Checks if given function raises an error
13156
13157 @method raises
13158 */
13159 function raises(fn, errorValidator) {
13160 check.verify.fn(fn, 'expected function that raises');
13161 try {
13162 fn();
13163 } catch (err) {
13164 if (typeof errorValidator === 'undefined') {
13165 return true;
13166 }
13167 if (typeof errorValidator === 'function') {
13168 return errorValidator(err);
13169 }
13170 return false;
13171 }
13172 // error has not been raised
13173 return false;
13174 }
13175
13176 /**
13177 Returns true if given value is ''
13178 @method emptyString
13179 */
13180 function emptyString(a) {
13181 return a === '';
13182 }
13183
13184 /**
13185 Returns true if given value is [], {} or ''
13186 @method empty
13187 */
13188 function empty(a) {
13189 var hasLength = typeof a === 'string' ||
13190 Array.isArray(a);
13191 if (hasLength) {
13192 return !a.length;
13193 }
13194 if (a instanceof Object) {
13195 return !Object.keys(a).length;
13196 }
13197 return false;
13198 }
13199
13200 /**
13201 Returns true if given value has .length and it is not zero, or has properties
13202 @method unempty
13203 */
13204 function unempty(a) {
13205 var hasLength = typeof a === 'string' ||
13206 Array.isArray(a);
13207 if (hasLength) {
13208 return a.length;
13209 }
13210 if (a instanceof Object) {
13211 return Object.keys(a).length;
13212 }
13213 return true;
13214 }
13215
13216 /**
13217 Returns true if 0 <= value <= 1
13218 @method unit
13219 */
13220 function unit(value) {
13221 return check.number(value) &&
13222 value >= 0.0 && value <= 1.0;
13223 }
13224
13225 var rgb = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
13226 /**
13227 Returns true if value is hex RGB between '#000000' and '#FFFFFF'
13228 @method hexRgb
13229 */
13230 function hexRgb(value) {
13231 return check.string(value) &&
13232 rgb.test(value);
13233 }
13234
13235 // typical git SHA commit id is 40 digit hex string, like
13236 // 3b819803cdf2225ca1338beb17e0c506fdeedefc
13237 var shaReg = /^[0-9a-f]{40}$/;
13238
13239 /**
13240 Returns true if the given string is 40 digit SHA commit id
13241 @method commitId
13242 */
13243 function commitId(id) {
13244 return check.string(id) &&
13245 id.length === 40 &&
13246 shaReg.test(id);
13247 }
13248
13249 // when using git log --oneline short ids are displayed, first 7 characters
13250 var shortShaReg = /^[0-9a-f]{7}$/;
13251
13252 /**
13253 Returns true if the given string is short 7 character SHA id part
13254 @method shortCommitId
13255 */
13256 function shortCommitId(id) {
13257 return check.string(id) &&
13258 id.length === 7 &&
13259 shortShaReg.test(id);
13260 }
13261
13262 //
13263 // helper methods
13264 //
13265
13266 if (!check.defend) {
13267 var checkPredicates = function checksPredicates(fn, predicates, args) {
13268 check.verify.fn(fn, 'expected a function');
13269 check.verify.array(predicates, 'expected list of predicates');
13270 check.verify.defined(args, 'missing args');
13271
13272 var k = 0, // iterates over predicates
13273 j = 0, // iterates over arguments
13274 n = predicates.length;
13275
13276 for (k = 0; k < n; k += 1) {
13277 var predicate = predicates[k];
13278 if (!check.fn(predicate)) {
13279 continue;
13280 }
13281
13282 if (!predicate.call(null, args[j])) {
13283 var msg = 'Argument ' + (j + 1) + ': ' + args[j] + ' does not pass predicate';
13284 if (check.unemptyString(predicates[k + 1])) {
13285 msg += ': ' + predicates[k + 1];
13286 }
13287 throw new Error(msg);
13288 }
13289
13290 j += 1;
13291 }
13292 return fn.apply(null, args);
13293 };
13294
13295 check.defend = function defend(fn) {
13296 var predicates = Array.prototype.slice.call(arguments, 1);
13297 return function () {
13298 return checkPredicates(fn, predicates, arguments);
13299 };
13300 };
13301 }
13302
13303 /**
13304 * Public modifier `not`.
13305 *
13306 * Negates `predicate`.
13307 * copied from check-types.js
13308 */
13309 function notModifier(predicate) {
13310 return function () {
13311 return !predicate.apply(null, arguments);
13312 };
13313 }
13314
13315 if (!check.mixin) {
13316 /** Adds new predicate to all objects
13317 @method mixin */
13318 check.mixin = function mixin(fn, name) {
13319 check.verify.fn(fn, 'expected predicate function');
13320 if (!check.unemptyString(name)) {
13321 name = fn.name;
13322 }
13323 check.verify.unemptyString(name, 'predicate function missing name\n' + fn.toString());
13324
13325 function registerPredicate(obj, name, fn) {
13326 check.verify.object(obj, 'missing object');
13327 check.verify.unemptyString(name, 'missing name');
13328 check.verify.fn(fn, 'missing function');
13329
13330 if (!obj[name]) {
13331 obj[name] = fn;
13332 }
13333 }
13334
13335 /**
13336 * Public modifier `maybe`.
13337 *
13338 * Returns `true` if `predicate` is `null` or `undefined`,
13339 * otherwise propagates the return value from `predicate`.
13340 * copied from check-types.js
13341 */
13342 function maybeModifier(predicate) {
13343 return function () {
13344 if (!check.defined(arguments[0]) || check.nulled(arguments[0])) {
13345 return true;
13346 }
13347 return predicate.apply(null, arguments);
13348 };
13349 }
13350
13351 /**
13352 * Public modifier `verify`.
13353 *
13354 * Throws if `predicate` returns `false`.
13355 * copied from check-types.js
13356 */
13357 function verifyModifier(predicate, defaultMessage) {
13358 return function () {
13359 var message;
13360 if (predicate.apply(null, arguments) === false) {
13361 message = arguments[arguments.length - 1];
13362 throw new Error(check.unemptyString(message) ? message : defaultMessage);
13363 }
13364 };
13365 }
13366
13367 registerPredicate(check, name, fn);
13368 registerPredicate(check.maybe, name, maybeModifier(fn));
13369 registerPredicate(check.not, name, notModifier(fn));
13370 registerPredicate(check.verify, name, verifyModifier(fn, name + ' failed'));
13371 };
13372 }
13373
13374 if (!check.then) {
13375 /**
13376 Executes given function only if condition is truthy.
13377 @method then
13378 */
13379 check.then = function then(condition, fn) {
13380 return function () {
13381 var ok = typeof condition === 'function' ?
13382 condition.apply(null, arguments) : condition;
13383 if (ok) {
13384 return fn.apply(null, arguments);
13385 }
13386 };
13387 };
13388 }
13389
13390 var promiseSchema = {
13391 then: check.fn
13392 };
13393
13394 // work around reserved keywords checks
13395 promiseSchema['catch'] = check.fn;
13396 promiseSchema['finally'] = check.fn;
13397
13398 var hasPromiseApi = schema.bind(null, promiseSchema);
13399
13400 /**
13401 Returns true if argument implements promise api (.then, .catch, .finally)
13402 @method promise
13403 */
13404 function isPromise(p) {
13405 return typeof p === 'object' &&
13406 hasPromiseApi(p);
13407 }
13408
13409 // new predicates to be added to check object. Use object to preserve names
13410 var predicates = {
13411 defined: defined,
13412 same: same,
13413 allSame: allSame,
13414 bit: bit,
13415 bool: bool,
13416 has: has,
13417 lowerCase: lowerCase,
13418 unemptyArray: unemptyArray,
13419 arrayOfStrings: arrayOfStrings,
13420 arrayOfArraysOfStrings: arrayOfArraysOfStrings,
13421 all: all,
13422 schema: schema,
13423 raises: raises,
13424 empty: empty,
13425 emptyString: emptyString,
13426 unempty: unempty,
13427 unit: unit,
13428 hexRgb: hexRgb,
13429 sameLength: sameLength,
13430 commitId: commitId,
13431 shortCommitId: shortCommitId,
13432 index: index,
13433 git: git,
13434 arrayOf: arrayOf,
13435 badItems: badItems,
13436 oneOf: oneOf,
13437 promise: isPromise
13438 };
13439
13440 Object.keys(predicates).forEach(function (name) {
13441 check.mixin(predicates[name], name);
13442 });
13443
13444 if (true) {
13445 module.exports = check;
13446 }
13447 }(typeof window === 'object' ? window.check : global.check));
13448
13449 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
13450
13451/***/ },
13452/* 11 */
13453/***/ function(module, exports, __webpack_require__) {
13454
13455 // Ramda v0.14.0
13456 // https://github.com/ramda/ramda
13457 // (c) 2013-2015 Scott Sauyet, Michael Hurley, and David Chambers
13458 // Ramda may be freely distributed under the MIT license.
13459
13460 ;(function() {
13461
13462 'use strict';
13463
13464 /**
13465 * A special placeholder value used to specify "gaps" within curried functions,
13466 * allowing partial application of any combination of arguments,
13467 * regardless of their positions.
13468 *
13469 * If `g` is a curried ternary function and `_` is `R.__`, the following are equivalent:
13470 *
13471 * - `g(1, 2, 3)`
13472 * - `g(_, 2, 3)(1)`
13473 * - `g(_, _, 3)(1)(2)`
13474 * - `g(_, _, 3)(1, 2)`
13475 * - `g(_, 2, _)(1, 3)`
13476 * - `g(_, 2)(1)(3)`
13477 * - `g(_, 2)(1, 3)`
13478 * - `g(_, 2)(_, 3)(1)`
13479 *
13480 * @constant
13481 * @memberOf R
13482 * @category Function
13483 * @example
13484 *
13485 * var greet = R.replace('{name}', R.__, 'Hello, {name}!');
13486 * greet('Alice'); //=> 'Hello, Alice!'
13487 */
13488 var __ = { ramda: 'placeholder' };
13489
13490 var _add = function _add(a, b) {
13491 return a + b;
13492 };
13493
13494 var _all = function _all(fn, list) {
13495 var idx = -1;
13496 while (++idx < list.length) {
13497 if (!fn(list[idx])) {
13498 return false;
13499 }
13500 }
13501 return true;
13502 };
13503
13504 var _any = function _any(fn, list) {
13505 var idx = -1;
13506 while (++idx < list.length) {
13507 if (fn(list[idx])) {
13508 return true;
13509 }
13510 }
13511 return false;
13512 };
13513
13514 var _assoc = function _assoc(prop, val, obj) {
13515 var result = {};
13516 for (var p in obj) {
13517 result[p] = obj[p];
13518 }
13519 result[prop] = val;
13520 return result;
13521 };
13522
13523 var _cloneRegExp = function _cloneRegExp(pattern) {
13524 return new RegExp(pattern.source, (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : ''));
13525 };
13526
13527 var _complement = function _complement(f) {
13528 return function () {
13529 return !f.apply(this, arguments);
13530 };
13531 };
13532
13533 /**
13534 * Basic, right-associative composition function. Accepts two functions and returns the
13535 * composite function; this composite function represents the operation `var h = f(g(x))`,
13536 * where `f` is the first argument, `g` is the second argument, and `x` is whatever
13537 * argument(s) are passed to `h`.
13538 *
13539 * This function's main use is to build the more general `compose` function, which accepts
13540 * any number of functions.
13541 *
13542 * @private
13543 * @category Function
13544 * @param {Function} f A function.
13545 * @param {Function} g A function.
13546 * @return {Function} A new function that is the equivalent of `f(g(x))`.
13547 * @example
13548 *
13549 * var double = function(x) { return x * 2; };
13550 * var square = function(x) { return x * x; };
13551 * var squareThenDouble = _compose(double, square);
13552 *
13553 * squareThenDouble(5); //≅ double(square(5)) => 50
13554 */
13555 var _compose = function _compose(f, g) {
13556 return function () {
13557 return f.call(this, g.apply(this, arguments));
13558 };
13559 };
13560
13561 /**
13562 * Private `concat` function to merge two array-like objects.
13563 *
13564 * @private
13565 * @param {Array|Arguments} [set1=[]] An array-like object.
13566 * @param {Array|Arguments} [set2=[]] An array-like object.
13567 * @return {Array} A new, merged array.
13568 * @example
13569 *
13570 * _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
13571 */
13572 var _concat = function _concat(set1, set2) {
13573 set1 = set1 || [];
13574 set2 = set2 || [];
13575 var idx;
13576 var len1 = set1.length;
13577 var len2 = set2.length;
13578 var result = [];
13579 idx = -1;
13580 while (++idx < len1) {
13581 result[result.length] = set1[idx];
13582 }
13583 idx = -1;
13584 while (++idx < len2) {
13585 result[result.length] = set2[idx];
13586 }
13587 return result;
13588 };
13589
13590 var _containsWith = function _containsWith(pred, x, list) {
13591 var idx = -1, len = list.length;
13592 while (++idx < len) {
13593 if (pred(x, list[idx])) {
13594 return true;
13595 }
13596 }
13597 return false;
13598 };
13599
13600 var _createMapEntry = function _createMapEntry(key, val) {
13601 var obj = {};
13602 obj[key] = val;
13603 return obj;
13604 };
13605
13606 /**
13607 * Create a function which takes a comparator function and a list
13608 * and determines the winning value by a compatator. Used internally
13609 * by `R.maxBy` and `R.minBy`
13610 *
13611 * @private
13612 * @param {Function} compatator a function to compare two items
13613 * @category Math
13614 * @return {Function}
13615 */
13616 var _createMaxMinBy = function _createMaxMinBy(comparator) {
13617 return function (valueComputer, list) {
13618 if (!(list && list.length > 0)) {
13619 return;
13620 }
13621 var idx = 0;
13622 var winner = list[idx];
13623 var computedWinner = valueComputer(winner);
13624 var computedCurrent;
13625 while (++idx < list.length) {
13626 computedCurrent = valueComputer(list[idx]);
13627 if (comparator(computedCurrent, computedWinner)) {
13628 computedWinner = computedCurrent;
13629 winner = list[idx];
13630 }
13631 }
13632 return winner;
13633 };
13634 };
13635
13636 /**
13637 * Optimized internal two-arity curry function.
13638 *
13639 * @private
13640 * @category Function
13641 * @param {Function} fn The function to curry.
13642 * @return {Function} The curried function.
13643 */
13644 var _curry1 = function _curry1(fn) {
13645 return function f1(a) {
13646 if (arguments.length === 0) {
13647 return f1;
13648 } else if (a === __) {
13649 return f1;
13650 } else {
13651 return fn(a);
13652 }
13653 };
13654 };
13655
13656 /**
13657 * Optimized internal two-arity curry function.
13658 *
13659 * @private
13660 * @category Function
13661 * @param {Function} fn The function to curry.
13662 * @return {Function} The curried function.
13663 */
13664 var _curry2 = function _curry2(fn) {
13665 return function f2(a, b) {
13666 var n = arguments.length;
13667 if (n === 0) {
13668 return f2;
13669 } else if (n === 1 && a === __) {
13670 return f2;
13671 } else if (n === 1) {
13672 return _curry1(function (b) {
13673 return fn(a, b);
13674 });
13675 } else if (n === 2 && a === __ && b === __) {
13676 return f2;
13677 } else if (n === 2 && a === __) {
13678 return _curry1(function (a) {
13679 return fn(a, b);
13680 });
13681 } else if (n === 2 && b === __) {
13682 return _curry1(function (b) {
13683 return fn(a, b);
13684 });
13685 } else {
13686 return fn(a, b);
13687 }
13688 };
13689 };
13690
13691 /**
13692 * Optimized internal three-arity curry function.
13693 *
13694 * @private
13695 * @category Function
13696 * @param {Function} fn The function to curry.
13697 * @return {Function} The curried function.
13698 */
13699 var _curry3 = function _curry3(fn) {
13700 return function f3(a, b, c) {
13701 var n = arguments.length;
13702 if (n === 0) {
13703 return f3;
13704 } else if (n === 1 && a === __) {
13705 return f3;
13706 } else if (n === 1) {
13707 return _curry2(function (b, c) {
13708 return fn(a, b, c);
13709 });
13710 } else if (n === 2 && a === __ && b === __) {
13711 return f3;
13712 } else if (n === 2 && a === __) {
13713 return _curry2(function (a, c) {
13714 return fn(a, b, c);
13715 });
13716 } else if (n === 2 && b === __) {
13717 return _curry2(function (b, c) {
13718 return fn(a, b, c);
13719 });
13720 } else if (n === 2) {
13721 return _curry1(function (c) {
13722 return fn(a, b, c);
13723 });
13724 } else if (n === 3 && a === __ && b === __ && c === __) {
13725 return f3;
13726 } else if (n === 3 && a === __ && b === __) {
13727 return _curry2(function (a, b) {
13728 return fn(a, b, c);
13729 });
13730 } else if (n === 3 && a === __ && c === __) {
13731 return _curry2(function (a, c) {
13732 return fn(a, b, c);
13733 });
13734 } else if (n === 3 && b === __ && c === __) {
13735 return _curry2(function (b, c) {
13736 return fn(a, b, c);
13737 });
13738 } else if (n === 3 && a === __) {
13739 return _curry1(function (a) {
13740 return fn(a, b, c);
13741 });
13742 } else if (n === 3 && b === __) {
13743 return _curry1(function (b) {
13744 return fn(a, b, c);
13745 });
13746 } else if (n === 3 && c === __) {
13747 return _curry1(function (c) {
13748 return fn(a, b, c);
13749 });
13750 } else {
13751 return fn(a, b, c);
13752 }
13753 };
13754 };
13755
13756 var _dissoc = function _dissoc(prop, obj) {
13757 var result = {};
13758 for (var p in obj) {
13759 if (p !== prop) {
13760 result[p] = obj[p];
13761 }
13762 }
13763 return result;
13764 };
13765
13766 var _eq = function _eq(a, b) {
13767 if (a === 0) {
13768 return 1 / a === 1 / b;
13769 } else {
13770 return a === b || a !== a && b !== b;
13771 }
13772 };
13773
13774 var _filter = function _filter(fn, list) {
13775 var idx = -1, len = list.length, result = [];
13776 while (++idx < len) {
13777 if (fn(list[idx])) {
13778 result[result.length] = list[idx];
13779 }
13780 }
13781 return result;
13782 };
13783
13784 var _filterIndexed = function _filterIndexed(fn, list) {
13785 var idx = -1, len = list.length, result = [];
13786 while (++idx < len) {
13787 if (fn(list[idx], idx, list)) {
13788 result[result.length] = list[idx];
13789 }
13790 }
13791 return result;
13792 };
13793
13794 // i can't bear not to return *something*
13795 var _forEach = function _forEach(fn, list) {
13796 var idx = -1, len = list.length;
13797 while (++idx < len) {
13798 fn(list[idx]);
13799 }
13800 // i can't bear not to return *something*
13801 return list;
13802 };
13803
13804 /**
13805 * @private
13806 * @param {Function} fn The strategy for extracting function names from an object
13807 * @return {Function} A function that takes an object and returns an array of function names.
13808 */
13809 var _functionsWith = function _functionsWith(fn) {
13810 return function (obj) {
13811 return _filter(function (key) {
13812 return typeof obj[key] === 'function';
13813 }, fn(obj));
13814 };
13815 };
13816
13817 var _gt = function _gt(a, b) {
13818 return a > b;
13819 };
13820
13821 var _has = function _has(prop, obj) {
13822 return Object.prototype.hasOwnProperty.call(obj, prop);
13823 };
13824
13825 var _identity = function _identity(x) {
13826 return x;
13827 };
13828
13829 var _indexOf = function _indexOf(list, item, from) {
13830 var idx = 0, len = list.length;
13831 if (typeof from == 'number') {
13832 idx = from < 0 ? Math.max(0, len + from) : from;
13833 }
13834 while (idx < len) {
13835 if (_eq(list[idx], item)) {
13836 return idx;
13837 }
13838 ++idx;
13839 }
13840 return -1;
13841 };
13842
13843 /**
13844 * Tests whether or not an object is an array.
13845 *
13846 * @private
13847 * @param {*} val The object to test.
13848 * @return {Boolean} `true` if `val` is an array, `false` otherwise.
13849 * @example
13850 *
13851 * _isArray([]); //=> true
13852 * _isArray(null); //=> false
13853 * _isArray({}); //=> false
13854 */
13855 var _isArray = Array.isArray || function _isArray(val) {
13856 return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]';
13857 };
13858
13859 /**
13860 * Determine if the passed argument is an integer.
13861 *
13862 * @private
13863 * @param {*} n
13864 * @category Type
13865 * @return {Boolean}
13866 */
13867 var _isInteger = Number.isInteger || function _isInteger(n) {
13868 return n << 0 === n;
13869 };
13870
13871 /**
13872 * Tests if a value is a thenable (promise).
13873 */
13874 var _isThenable = function _isThenable(value) {
13875 return value != null && value === Object(value) && typeof value.then === 'function';
13876 };
13877
13878 var _isTransformer = function _isTransformer(obj) {
13879 return typeof obj['@@transducer/step'] === 'function';
13880 };
13881
13882 var _lastIndexOf = function _lastIndexOf(list, item, from) {
13883 var idx = list.length;
13884 if (typeof from == 'number') {
13885 idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
13886 }
13887 while (--idx >= 0) {
13888 if (_eq(list[idx], item)) {
13889 return idx;
13890 }
13891 }
13892 return -1;
13893 };
13894
13895 var _lt = function _lt(a, b) {
13896 return a < b;
13897 };
13898
13899 var _map = function _map(fn, list) {
13900 var idx = -1, len = list.length, result = [];
13901 while (++idx < len) {
13902 result[idx] = fn(list[idx]);
13903 }
13904 return result;
13905 };
13906
13907 var _multiply = function _multiply(a, b) {
13908 return a * b;
13909 };
13910
13911 var _nth = function _nth(n, list) {
13912 return n < 0 ? list[list.length + n] : list[n];
13913 };
13914
13915 /**
13916 * internal path function
13917 * Takes an array, paths, indicating the deep set of keys
13918 * to find.
13919 *
13920 * @private
13921 * @memberOf R
13922 * @category Object
13923 * @param {Array} paths An array of strings to map to object properties
13924 * @param {Object} obj The object to find the path in
13925 * @return {Array} The value at the end of the path or `undefined`.
13926 * @example
13927 *
13928 * _path(['a', 'b'], {a: {b: 2}}); //=> 2
13929 */
13930 var _path = function _path(paths, obj) {
13931 if (obj == null) {
13932 return;
13933 } else {
13934 var val = obj;
13935 for (var idx = 0, len = paths.length; idx < len && val != null; idx += 1) {
13936 val = val[paths[idx]];
13937 }
13938 return val;
13939 }
13940 };
13941
13942 var _prepend = function _prepend(el, list) {
13943 return _concat([el], list);
13944 };
13945
13946 var _quote = function _quote(s) {
13947 return '"' + s.replace(/"/g, '\\"') + '"';
13948 };
13949
13950 var _reduced = function (x) {
13951 return x && x['@@transducer/reduced'] ? x : {
13952 '@@transducer/value': x,
13953 '@@transducer/reduced': true
13954 };
13955 };
13956
13957 /**
13958 * An optimized, private array `slice` implementation.
13959 *
13960 * @private
13961 * @param {Arguments|Array} args The array or arguments object to consider.
13962 * @param {Number} [from=0] The array index to slice from, inclusive.
13963 * @param {Number} [to=args.length] The array index to slice to, exclusive.
13964 * @return {Array} A new, sliced array.
13965 * @example
13966 *
13967 * _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3]
13968 *
13969 * var firstThreeArgs = function(a, b, c, d) {
13970 * return _slice(arguments, 0, 3);
13971 * };
13972 * firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3]
13973 */
13974 var _slice = function _slice(args, from, to) {
13975 switch (arguments.length) {
13976 case 1:
13977 return _slice(args, 0, args.length);
13978 case 2:
13979 return _slice(args, from, args.length);
13980 default:
13981 var list = [];
13982 var idx = -1;
13983 var len = Math.max(0, Math.min(args.length, to) - from);
13984 while (++idx < len) {
13985 list[idx] = args[from + idx];
13986 }
13987 return list;
13988 }
13989 };
13990
13991 /**
13992 * Polyfill from <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString>.
13993 */
13994 var _toISOString = function () {
13995 var pad = function pad(n) {
13996 return (n < 10 ? '0' : '') + n;
13997 };
13998 return typeof Date.prototype.toISOString === 'function' ? function _toISOString(d) {
13999 return d.toISOString();
14000 } : function _toISOString(d) {
14001 return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) + '.' + (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z';
14002 };
14003 }();
14004
14005 var _xdropRepeatsWith = function () {
14006 function XDropRepeatsWith(pred, xf) {
14007 this.xf = xf;
14008 this.pred = pred;
14009 this.lastValue = undefined;
14010 this.seenFirstValue = false;
14011 }
14012 XDropRepeatsWith.prototype['@@transducer/init'] = function () {
14013 return this.xf['@@transducer/init']();
14014 };
14015 XDropRepeatsWith.prototype['@@transducer/result'] = function (result) {
14016 return this.xf['@@transducer/result'](result);
14017 };
14018 XDropRepeatsWith.prototype['@@transducer/step'] = function (result, input) {
14019 var sameAsLast = false;
14020 if (!this.seenFirstValue) {
14021 this.seenFirstValue = true;
14022 } else if (this.pred(this.lastValue, input)) {
14023 sameAsLast = true;
14024 }
14025 this.lastValue = input;
14026 return sameAsLast ? result : this.xf['@@transducer/step'](result, input);
14027 };
14028 return _curry2(function _xdropRepeatsWith(pred, xf) {
14029 return new XDropRepeatsWith(pred, xf);
14030 });
14031 }();
14032
14033 var _xfBase = {
14034 init: function () {
14035 return this.xf['@@transducer/init']();
14036 },
14037 result: function (result) {
14038 return this.xf['@@transducer/result'](result);
14039 }
14040 };
14041
14042 var _xfilter = function () {
14043 function XFilter(f, xf) {
14044 this.xf = xf;
14045 this.f = f;
14046 }
14047 XFilter.prototype['@@transducer/init'] = _xfBase.init;
14048 XFilter.prototype['@@transducer/result'] = _xfBase.result;
14049 XFilter.prototype['@@transducer/step'] = function (result, input) {
14050 return this.f(input) ? this.xf['@@transducer/step'](result, input) : result;
14051 };
14052 return _curry2(function _xfilter(f, xf) {
14053 return new XFilter(f, xf);
14054 });
14055 }();
14056
14057 var _xfind = function () {
14058 function XFind(f, xf) {
14059 this.xf = xf;
14060 this.f = f;
14061 this.found = false;
14062 }
14063 XFind.prototype['@@transducer/init'] = _xfBase.init;
14064 XFind.prototype['@@transducer/result'] = function (result) {
14065 if (!this.found) {
14066 result = this.xf['@@transducer/step'](result, void 0);
14067 }
14068 return this.xf['@@transducer/result'](result);
14069 };
14070 XFind.prototype['@@transducer/step'] = function (result, input) {
14071 if (this.f(input)) {
14072 this.found = true;
14073 result = _reduced(this.xf['@@transducer/step'](result, input));
14074 }
14075 return result;
14076 };
14077 return _curry2(function _xfind(f, xf) {
14078 return new XFind(f, xf);
14079 });
14080 }();
14081
14082 var _xfindIndex = function () {
14083 function XFindIndex(f, xf) {
14084 this.xf = xf;
14085 this.f = f;
14086 this.idx = -1;
14087 this.found = false;
14088 }
14089 XFindIndex.prototype['@@transducer/init'] = _xfBase.init;
14090 XFindIndex.prototype['@@transducer/result'] = function (result) {
14091 if (!this.found) {
14092 result = this.xf['@@transducer/step'](result, -1);
14093 }
14094 return this.xf['@@transducer/result'](result);
14095 };
14096 XFindIndex.prototype['@@transducer/step'] = function (result, input) {
14097 this.idx += 1;
14098 if (this.f(input)) {
14099 this.found = true;
14100 result = _reduced(this.xf['@@transducer/step'](result, this.idx));
14101 }
14102 return result;
14103 };
14104 return _curry2(function _xfindIndex(f, xf) {
14105 return new XFindIndex(f, xf);
14106 });
14107 }();
14108
14109 var _xfindLast = function () {
14110 function XFindLast(f, xf) {
14111 this.xf = xf;
14112 this.f = f;
14113 }
14114 XFindLast.prototype['@@transducer/init'] = _xfBase.init;
14115 XFindLast.prototype['@@transducer/result'] = function (result) {
14116 return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.last));
14117 };
14118 XFindLast.prototype['@@transducer/step'] = function (result, input) {
14119 if (this.f(input)) {
14120 this.last = input;
14121 }
14122 return result;
14123 };
14124 return _curry2(function _xfindLast(f, xf) {
14125 return new XFindLast(f, xf);
14126 });
14127 }();
14128
14129 var _xfindLastIndex = function () {
14130 function XFindLastIndex(f, xf) {
14131 this.xf = xf;
14132 this.f = f;
14133 this.idx = -1;
14134 this.lastIdx = -1;
14135 }
14136 XFindLastIndex.prototype['@@transducer/init'] = _xfBase.init;
14137 XFindLastIndex.prototype['@@transducer/result'] = function (result) {
14138 return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.lastIdx));
14139 };
14140 XFindLastIndex.prototype['@@transducer/step'] = function (result, input) {
14141 this.idx += 1;
14142 if (this.f(input)) {
14143 this.lastIdx = this.idx;
14144 }
14145 return result;
14146 };
14147 return _curry2(function _xfindLastIndex(f, xf) {
14148 return new XFindLastIndex(f, xf);
14149 });
14150 }();
14151
14152 var _xmap = function () {
14153 function XMap(f, xf) {
14154 this.xf = xf;
14155 this.f = f;
14156 }
14157 XMap.prototype['@@transducer/init'] = _xfBase.init;
14158 XMap.prototype['@@transducer/result'] = _xfBase.result;
14159 XMap.prototype['@@transducer/step'] = function (result, input) {
14160 return this.xf['@@transducer/step'](result, this.f(input));
14161 };
14162 return _curry2(function _xmap(f, xf) {
14163 return new XMap(f, xf);
14164 });
14165 }();
14166
14167 var _xtake = function () {
14168 function XTake(n, xf) {
14169 this.xf = xf;
14170 this.n = n;
14171 }
14172 XTake.prototype['@@transducer/init'] = _xfBase.init;
14173 XTake.prototype['@@transducer/result'] = _xfBase.result;
14174 XTake.prototype['@@transducer/step'] = function (result, input) {
14175 this.n -= 1;
14176 return this.n === 0 ? _reduced(this.xf['@@transducer/step'](result, input)) : this.xf['@@transducer/step'](result, input);
14177 };
14178 return _curry2(function _xtake(n, xf) {
14179 return new XTake(n, xf);
14180 });
14181 }();
14182
14183 var _xtakeWhile = function () {
14184 function XTakeWhile(f, xf) {
14185 this.xf = xf;
14186 this.f = f;
14187 }
14188 XTakeWhile.prototype['@@transducer/init'] = _xfBase.init;
14189 XTakeWhile.prototype['@@transducer/result'] = _xfBase.result;
14190 XTakeWhile.prototype['@@transducer/step'] = function (result, input) {
14191 return this.f(input) ? this.xf['@@transducer/step'](result, input) : _reduced(result);
14192 };
14193 return _curry2(function _xtakeWhile(f, xf) {
14194 return new XTakeWhile(f, xf);
14195 });
14196 }();
14197
14198 var _xwrap = function () {
14199 function XWrap(fn) {
14200 this.f = fn;
14201 }
14202 XWrap.prototype['@@transducer/init'] = function () {
14203 throw new Error('init not implemented on XWrap');
14204 };
14205 XWrap.prototype['@@transducer/result'] = function (acc) {
14206 return acc;
14207 };
14208 XWrap.prototype['@@transducer/step'] = function (acc, x) {
14209 return this.f(acc, x);
14210 };
14211 return function _xwrap(fn) {
14212 return new XWrap(fn);
14213 };
14214 }();
14215
14216 /**
14217 * Adds two numbers (or strings). Equivalent to `a + b` but curried.
14218 *
14219 * @func
14220 * @memberOf R
14221 * @category Math
14222 * @sig Number -> Number -> Number
14223 * @sig String -> String -> String
14224 * @param {Number|String} a The first value.
14225 * @param {Number|String} b The second value.
14226 * @return {Number|String} The result of `a + b`.
14227 * @example
14228 *
14229 * R.add(2, 3); //=> 5
14230 * R.add(7)(10); //=> 17
14231 */
14232 var add = _curry2(_add);
14233
14234 /**
14235 * Applies a function to the value at the given index of an array,
14236 * returning a new copy of the array with the element at the given
14237 * index replaced with the result of the function application.
14238 *
14239 * @func
14240 * @memberOf R
14241 * @category List
14242 * @sig (a -> a) -> Number -> [a] -> [a]
14243 * @param {Function} fn The function to apply.
14244 * @param {Number} idx The index.
14245 * @param {Array|Arguments} list An array-like object whose value
14246 * at the supplied index will be replaced.
14247 * @return {Array} A copy of the supplied array-like object with
14248 * the element at index `idx` replaced with the value
14249 * returned by applying `fn` to the existing element.
14250 * @example
14251 *
14252 * R.adjust(R.add(10), 1, [0, 1, 2]); //=> [0, 11, 2]
14253 * R.adjust(R.add(10))(1)([0, 1, 2]); //=> [0, 11, 2]
14254 */
14255 var adjust = _curry3(function (fn, idx, list) {
14256 if (idx >= list.length || idx < -list.length) {
14257 return list;
14258 }
14259 var start = idx < 0 ? list.length : 0;
14260 var _idx = start + idx;
14261 var _list = _concat(list);
14262 _list[_idx] = fn(list[_idx]);
14263 return _list;
14264 });
14265
14266 /**
14267 * Returns a function that always returns the given value. Note that for non-primitives the value
14268 * returned is a reference to the original value.
14269 *
14270 * @func
14271 * @memberOf R
14272 * @category Function
14273 * @sig a -> (* -> a)
14274 * @param {*} val The value to wrap in a function
14275 * @return {Function} A Function :: * -> val.
14276 * @example
14277 *
14278 * var t = R.always('Tee');
14279 * t(); //=> 'Tee'
14280 */
14281 var always = _curry1(function always(val) {
14282 return function () {
14283 return val;
14284 };
14285 });
14286
14287 /**
14288 * Returns a new list, composed of n-tuples of consecutive elements
14289 * If `n` is greater than the length of the list, an empty list is returned.
14290 *
14291 * @func
14292 * @memberOf R
14293 * @category List
14294 * @sig Number -> [a] -> [[a]]
14295 * @param {Number} n The size of the tuples to create
14296 * @param {Array} list The list to split into `n`-tuples
14297 * @return {Array} The new list.
14298 * @example
14299 *
14300 * R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]]
14301 * R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
14302 * R.aperture(7, [1, 2, 3, 4, 5]); //=> []
14303 */
14304 var aperture = _curry2(function aperture(n, list) {
14305 var idx = -1;
14306 var limit = list.length - (n - 1);
14307 var acc = new Array(limit >= 0 ? limit : 0);
14308 while (++idx < limit) {
14309 acc[idx] = _slice(list, idx, idx + n);
14310 }
14311 return acc;
14312 });
14313
14314 /**
14315 * Applies function `fn` to the argument list `args`. This is useful for
14316 * creating a fixed-arity function from a variadic function. `fn` should
14317 * be a bound function if context is significant.
14318 *
14319 * @func
14320 * @memberOf R
14321 * @category Function
14322 * @sig (*... -> a) -> [*] -> a
14323 * @param {Function} fn
14324 * @param {Array} args
14325 * @return {*}
14326 * @example
14327 *
14328 * var nums = [1, 2, 3, -99, 42, 6, 7];
14329 * R.apply(Math.max, nums); //=> 42
14330 */
14331 var apply = _curry2(function apply(fn, args) {
14332 return fn.apply(this, args);
14333 });
14334
14335 /**
14336 * Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
14337 * parameters. Unlike `nAry`, which passes only `n` arguments to the wrapped function,
14338 * functions produced by `arity` will pass all provided arguments to the wrapped function.
14339 *
14340 * @func
14341 * @memberOf R
14342 * @sig (Number, (* -> *)) -> (* -> *)
14343 * @category Function
14344 * @param {Number} n The desired arity of the returned function.
14345 * @param {Function} fn The function to wrap.
14346 * @return {Function} A new function wrapping `fn`. The new function is
14347 * guaranteed to be of arity `n`.
14348 * @example
14349 *
14350 * var takesTwoArgs = function(a, b) {
14351 * return [a, b];
14352 * };
14353 * takesTwoArgs.length; //=> 2
14354 * takesTwoArgs(1, 2); //=> [1, 2]
14355 *
14356 * var takesOneArg = R.arity(1, takesTwoArgs);
14357 * takesOneArg.length; //=> 1
14358 * // All arguments are passed through to the wrapped function
14359 * takesOneArg(1, 2); //=> [1, 2]
14360 */
14361 var arity = _curry2(function (n, fn) {
14362 switch (n) {
14363 case 0:
14364 return function () {
14365 return fn.apply(this, arguments);
14366 };
14367 case 1:
14368 return function (a0) {
14369 void a0;
14370 return fn.apply(this, arguments);
14371 };
14372 case 2:
14373 return function (a0, a1) {
14374 void a1;
14375 return fn.apply(this, arguments);
14376 };
14377 case 3:
14378 return function (a0, a1, a2) {
14379 void a2;
14380 return fn.apply(this, arguments);
14381 };
14382 case 4:
14383 return function (a0, a1, a2, a3) {
14384 void a3;
14385 return fn.apply(this, arguments);
14386 };
14387 case 5:
14388 return function (a0, a1, a2, a3, a4) {
14389 void a4;
14390 return fn.apply(this, arguments);
14391 };
14392 case 6:
14393 return function (a0, a1, a2, a3, a4, a5) {
14394 void a5;
14395 return fn.apply(this, arguments);
14396 };
14397 case 7:
14398 return function (a0, a1, a2, a3, a4, a5, a6) {
14399 void a6;
14400 return fn.apply(this, arguments);
14401 };
14402 case 8:
14403 return function (a0, a1, a2, a3, a4, a5, a6, a7) {
14404 void a7;
14405 return fn.apply(this, arguments);
14406 };
14407 case 9:
14408 return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
14409 void a8;
14410 return fn.apply(this, arguments);
14411 };
14412 case 10:
14413 return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
14414 void a9;
14415 return fn.apply(this, arguments);
14416 };
14417 default:
14418 throw new Error('First argument to arity must be a non-negative integer no greater than ten');
14419 }
14420 });
14421
14422 /**
14423 * Makes a shallow clone of an object, setting or overriding the specified
14424 * property with the given value. Note that this copies and flattens
14425 * prototype properties onto the new object as well. All non-primitive
14426 * properties are copied by reference.
14427 *
14428 * @func
14429 * @memberOf R
14430 * @category Object
14431 * @sig String -> a -> {k: v} -> {k: v}
14432 * @param {String} prop the property name to set
14433 * @param {*} val the new value
14434 * @param {Object} obj the object to clone
14435 * @return {Object} a new object similar to the original except for the specified property.
14436 * @example
14437 *
14438 * R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}
14439 */
14440 var assoc = _curry3(_assoc);
14441
14442 /**
14443 * Creates a function that is bound to a context.
14444 * Note: `R.bind` does not provide the additional argument-binding capabilities of
14445 * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
14446 *
14447 * @func
14448 * @memberOf R
14449 * @category Function
14450 * @category Object
14451 * @see R.partial
14452 * @sig (* -> *) -> {*} -> (* -> *)
14453 * @param {Function} fn The function to bind to context
14454 * @param {Object} thisObj The context to bind `fn` to
14455 * @return {Function} A function that will execute in the context of `thisObj`.
14456 */
14457 var bind = _curry2(function bind(fn, thisObj) {
14458 return arity(fn.length, function () {
14459 return fn.apply(thisObj, arguments);
14460 });
14461 });
14462
14463 /**
14464 * A function wrapping calls to the two functions in an `&&` operation, returning the result of the first
14465 * function if it is false-y and the result of the second function otherwise. Note that this is
14466 * short-circuited, meaning that the second function will not be invoked if the first returns a false-y
14467 * value.
14468 *
14469 * @func
14470 * @memberOf R
14471 * @category Logic
14472 * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
14473 * @param {Function} f a predicate
14474 * @param {Function} g another predicate
14475 * @return {Function} a function that applies its arguments to `f` and `g` and `&&`s their outputs together.
14476 * @example
14477 *
14478 * var gt10 = function(x) { return x > 10; };
14479 * var even = function(x) { return x % 2 === 0 };
14480 * var f = R.both(gt10, even);
14481 * f(100); //=> true
14482 * f(101); //=> false
14483 */
14484 var both = _curry2(function both(f, g) {
14485 return function _both() {
14486 return f.apply(this, arguments) && g.apply(this, arguments);
14487 };
14488 });
14489
14490 /**
14491 * Makes a comparator function out of a function that reports whether the first element is less than the second.
14492 *
14493 * @func
14494 * @memberOf R
14495 * @category Function
14496 * @sig (a, b -> Boolean) -> (a, b -> Number)
14497 * @param {Function} pred A predicate function of arity two.
14498 * @return {Function} A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`.
14499 * @example
14500 *
14501 * var cmp = R.comparator(function(a, b) {
14502 * return a.age < b.age;
14503 * });
14504 * var people = [
14505 * // ...
14506 * ];
14507 * R.sort(cmp, people);
14508 */
14509 var comparator = _curry1(function comparator(pred) {
14510 return function (a, b) {
14511 return pred(a, b) ? -1 : pred(b, a) ? 1 : 0;
14512 };
14513 });
14514
14515 /**
14516 * Takes a function `f` and returns a function `g` such that:
14517 *
14518 * - applying `g` to zero or more arguments will give __true__ if applying
14519 * the same arguments to `f` gives a logical __false__ value; and
14520 *
14521 * - applying `g` to zero or more arguments will give __false__ if applying
14522 * the same arguments to `f` gives a logical __true__ value.
14523 *
14524 * @func
14525 * @memberOf R
14526 * @category Logic
14527 * @sig (*... -> *) -> (*... -> Boolean)
14528 * @param {Function} f
14529 * @return {Function}
14530 * @example
14531 *
14532 * var isEven = function(n) { return n % 2 === 0; };
14533 * var isOdd = R.complement(isEven);
14534 * isOdd(21); //=> true
14535 * isOdd(42); //=> false
14536 */
14537 var complement = _curry1(_complement);
14538
14539 /**
14540 * Returns a function, `fn`, which encapsulates if/else-if/else logic.
14541 * Each argument to `R.cond` is a [predicate, transform] pair. All of
14542 * the arguments to `fn` are applied to each of the predicates in turn
14543 * until one returns a "truthy" value, at which point `fn` returns the
14544 * result of applying its arguments to the corresponding transformer.
14545 * If none of the predicates matches, `fn` returns undefined.
14546 *
14547 * @func
14548 * @memberOf R
14549 * @category Logic
14550 * @sig [(*... -> Boolean),(*... -> *)]... -> (*... -> *)
14551 * @param {...Function} functions
14552 * @return {Function}
14553 * @example
14554 *
14555 * var fn = R.cond(
14556 * [R.eq(0), R.always('water freezes at 0°C')],
14557 * [R.eq(100), R.always('water boils at 100°C')],
14558 * [R.T, function(temp) { return 'nothing special happens at ' + temp + '°C'; }]
14559 * );
14560 * fn(0); //=> 'water freezes at 0°C'
14561 * fn(50); //=> 'nothing special happens at 50°C'
14562 * fn(100); //=> 'water boils at 100°C'
14563 */
14564 var cond = function cond() {
14565 var pairs = arguments;
14566 return function () {
14567 var idx = -1;
14568 while (++idx < pairs.length) {
14569 if (pairs[idx][0].apply(this, arguments)) {
14570 return pairs[idx][1].apply(this, arguments);
14571 }
14572 }
14573 };
14574 };
14575
14576 /**
14577 * Returns `true` if the `x` is found in the `list`, using `pred` as an
14578 * equality predicate for `x`.
14579 *
14580 * @func
14581 * @memberOf R
14582 * @category List
14583 * @sig (a, a -> Boolean) -> a -> [a] -> Boolean
14584 * @param {Function} pred A predicate used to test whether two items are equal.
14585 * @param {*} x The item to find
14586 * @param {Array} list The list to iterate over
14587 * @return {Boolean} `true` if `x` is in `list`, else `false`.
14588 * @example
14589 *
14590 * var xs = [{x: 12}, {x: 11}, {x: 10}];
14591 * R.containsWith(function(a, b) { return a.x === b.x; }, {x: 10}, xs); //=> true
14592 * R.containsWith(function(a, b) { return a.x === b.x; }, {x: 1}, xs); //=> false
14593 */
14594 var containsWith = _curry3(_containsWith);
14595
14596 /**
14597 * Counts the elements of a list according to how many match each value
14598 * of a key generated by the supplied function. Returns an object
14599 * mapping the keys produced by `fn` to the number of occurrences in
14600 * the list. Note that all keys are coerced to strings because of how
14601 * JavaScript objects work.
14602 *
14603 * @func
14604 * @memberOf R
14605 * @category Relation
14606 * @sig (a -> String) -> [a] -> {*}
14607 * @param {Function} fn The function used to map values to keys.
14608 * @param {Array} list The list to count elements from.
14609 * @return {Object} An object mapping keys to number of occurrences in the list.
14610 * @example
14611 *
14612 * var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
14613 * var letters = R.split('', 'abcABCaaaBBc');
14614 * R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
14615 * R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3}
14616 */
14617 var countBy = _curry2(function countBy(fn, list) {
14618 var counts = {};
14619 var len = list.length;
14620 var idx = -1;
14621 while (++idx < len) {
14622 var key = fn(list[idx]);
14623 counts[key] = (_has(key, counts) ? counts[key] : 0) + 1;
14624 }
14625 return counts;
14626 });
14627
14628 /**
14629 * Creates an object containing a single key:value pair.
14630 *
14631 * @func
14632 * @memberOf R
14633 * @category Object
14634 * @sig String -> a -> {String:a}
14635 * @param {String} key
14636 * @param {*} val
14637 * @return {Object}
14638 * @example
14639 *
14640 * var matchPhrases = R.compose(
14641 * R.createMapEntry('must'),
14642 * R.map(R.createMapEntry('match_phrase'))
14643 * );
14644 * matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]}
14645 */
14646 var createMapEntry = _curry2(_createMapEntry);
14647
14648 /**
14649 * Returns a curried equivalent of the provided function, with the
14650 * specified arity. The curried function has two unusual capabilities.
14651 * First, its arguments needn't be provided one at a time. If `g` is
14652 * `R.curryN(3, f)`, the following are equivalent:
14653 *
14654 * - `g(1)(2)(3)`
14655 * - `g(1)(2, 3)`
14656 * - `g(1, 2)(3)`
14657 * - `g(1, 2, 3)`
14658 *
14659 * Secondly, the special placeholder value `R.__` may be used to specify
14660 * "gaps", allowing partial application of any combination of arguments,
14661 * regardless of their positions. If `g` is as above and `_` is `R.__`,
14662 * the following are equivalent:
14663 *
14664 * - `g(1, 2, 3)`
14665 * - `g(_, 2, 3)(1)`
14666 * - `g(_, _, 3)(1)(2)`
14667 * - `g(_, _, 3)(1, 2)`
14668 * - `g(_, 2)(1)(3)`
14669 * - `g(_, 2)(1, 3)`
14670 * - `g(_, 2)(_, 3)(1)`
14671 *
14672 * @func
14673 * @memberOf R
14674 * @category Function
14675 * @sig Number -> (* -> a) -> (* -> a)
14676 * @param {Number} length The arity for the returned function.
14677 * @param {Function} fn The function to curry.
14678 * @return {Function} A new, curried function.
14679 * @see R.curry
14680 * @example
14681 *
14682 * var addFourNumbers = function() {
14683 * return R.sum([].slice.call(arguments, 0, 4));
14684 * };
14685 *
14686 * var curriedAddFourNumbers = R.curryN(4, addFourNumbers);
14687 * var f = curriedAddFourNumbers(1, 2);
14688 * var g = f(3);
14689 * g(4); //=> 10
14690 */
14691 var curryN = _curry2(function curryN(length, fn) {
14692 return arity(length, function () {
14693 var n = arguments.length;
14694 var shortfall = length - n;
14695 var idx = n;
14696 while (--idx >= 0) {
14697 if (arguments[idx] === __) {
14698 shortfall += 1;
14699 }
14700 }
14701 if (shortfall <= 0) {
14702 return fn.apply(this, arguments);
14703 } else {
14704 var initialArgs = _slice(arguments);
14705 return curryN(shortfall, function () {
14706 var currentArgs = _slice(arguments);
14707 var combinedArgs = [];
14708 var idx = -1;
14709 while (++idx < n) {
14710 var val = initialArgs[idx];
14711 combinedArgs[idx] = val === __ ? currentArgs.shift() : val;
14712 }
14713 return fn.apply(this, combinedArgs.concat(currentArgs));
14714 });
14715 }
14716 });
14717 });
14718
14719 /**
14720 * Decrements its argument.
14721 *
14722 * @func
14723 * @memberOf R
14724 * @category Math
14725 * @sig Number -> Number
14726 * @param {Number} n
14727 * @return {Number}
14728 * @example
14729 *
14730 * R.dec(42); //=> 41
14731 */
14732 var dec = add(-1);
14733
14734 /**
14735 * Returns the second argument if it is not null or undefined. If it is null
14736 * or undefined, the first (default) argument is returned.
14737 *
14738 * @func
14739 * @memberOf R
14740 * @category Logic
14741 * @sig a -> b -> a | b
14742 * @param {a} val The default value.
14743 * @param {b} val The value to return if it is not null or undefined
14744 * @return {*} The the second value or the default value
14745 * @example
14746 *
14747 * var defaultTo42 = defaultTo(42);
14748 *
14749 * defaultTo42(null); //=> 42
14750 * defaultTo42(undefined); //=> 42
14751 * defaultTo42('Ramda'); //=> 'Ramda'
14752 */
14753 var defaultTo = _curry2(function defaultTo(d, v) {
14754 return v == null ? d : v;
14755 });
14756
14757 /**
14758 * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
14759 * Duplication is determined according to the value returned by applying the supplied predicate to two list
14760 * elements.
14761 *
14762 * @func
14763 * @memberOf R
14764 * @category Relation
14765 * @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
14766 * @param {Function} pred A predicate used to test whether two items are equal.
14767 * @param {Array} list1 The first list.
14768 * @param {Array} list2 The second list.
14769 * @see R.difference
14770 * @return {Array} The elements in `list1` that are not in `list2`.
14771 * @example
14772 *
14773 * function cmp(x, y) { return x.a === y.a; }
14774 * var l1 = [{a: 1}, {a: 2}, {a: 3}];
14775 * var l2 = [{a: 3}, {a: 4}];
14776 * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]
14777 */
14778 var differenceWith = _curry3(function differenceWith(pred, first, second) {
14779 var out = [];
14780 var idx = -1;
14781 var firstLen = first.length;
14782 var containsPred = containsWith(pred);
14783 while (++idx < firstLen) {
14784 if (!containsPred(first[idx], second) && !containsPred(first[idx], out)) {
14785 out[out.length] = first[idx];
14786 }
14787 }
14788 return out;
14789 });
14790
14791 /**
14792 * Returns a new object that does not contain a `prop` property.
14793 *
14794 * @func
14795 * @memberOf R
14796 * @category Object
14797 * @sig String -> {k: v} -> {k: v}
14798 * @param {String} prop the name of the property to dissociate
14799 * @param {Object} obj the object to clone
14800 * @return {Object} a new object similar to the original but without the specified property
14801 * @example
14802 *
14803 * R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3}
14804 */
14805 var dissoc = _curry2(_dissoc);
14806
14807 /**
14808 * Divides two numbers. Equivalent to `a / b`.
14809 *
14810 * @func
14811 * @memberOf R
14812 * @category Math
14813 * @sig Number -> Number -> Number
14814 * @param {Number} a The first value.
14815 * @param {Number} b The second value.
14816 * @return {Number} The result of `a / b`.
14817 * @example
14818 *
14819 * R.divide(71, 100); //=> 0.71
14820 *
14821 * var half = R.divide(R.__, 2);
14822 * half(42); //=> 21
14823 *
14824 * var reciprocal = R.divide(1);
14825 * reciprocal(4); //=> 0.25
14826 */
14827 var divide = _curry2(function divide(a, b) {
14828 return a / b;
14829 });
14830
14831 /**
14832 * A function wrapping calls to the two functions in an `||` operation, returning the result of the first
14833 * function if it is truth-y and the result of the second function otherwise. Note that this is
14834 * short-circuited, meaning that the second function will not be invoked if the first returns a truth-y
14835 * value.
14836 *
14837 * @func
14838 * @memberOf R
14839 * @category Logic
14840 * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
14841 * @param {Function} f a predicate
14842 * @param {Function} g another predicate
14843 * @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together.
14844 * @example
14845 *
14846 * var gt10 = function(x) { return x > 10; };
14847 * var even = function(x) { return x % 2 === 0 };
14848 * var f = R.either(gt10, even);
14849 * f(101); //=> true
14850 * f(8); //=> true
14851 */
14852 var either = _curry2(function either(f, g) {
14853 return function _either() {
14854 return f.apply(this, arguments) || g.apply(this, arguments);
14855 };
14856 });
14857
14858 /**
14859 * Tests if two items are equal. Equality is strict here, meaning reference equality for objects and
14860 * non-coercing equality for primitives.
14861 *
14862 * Has `Object.is` semantics: `NaN` is considered equal to `NaN`; `0` and `-0`
14863 * are not considered equal.
14864 *
14865 * @func
14866 * @memberOf R
14867 * @category Relation
14868 * @sig a -> a -> Boolean
14869 * @param {*} a
14870 * @param {*} b
14871 * @return {Boolean}
14872 * @example
14873 *
14874 * var o = {};
14875 * R.eq(o, o); //=> true
14876 * R.eq(o, {}); //=> false
14877 * R.eq(1, 1); //=> true
14878 * R.eq(1, '1'); //=> false
14879 * R.eq(0, -0); //=> false
14880 * R.eq(NaN, NaN); //=> true
14881 */
14882 var eq = _curry2(_eq);
14883
14884 /**
14885 * Reports whether two objects have the same value for the specified property. Useful as a curried predicate.
14886 *
14887 * Has `Object.is` semantics: `NaN` is considered equal to `NaN`; `0` and `-0`
14888 * are not considered equal.
14889 *
14890 * @func
14891 * @memberOf R
14892 * @category Object
14893 * @sig k -> {k: v} -> {k: v} -> Boolean
14894 * @param {String} prop The name of the property to compare
14895 * @param {Object} obj1
14896 * @param {Object} obj2
14897 * @return {Boolean}
14898 *
14899 * @example
14900 *
14901 * var o1 = { a: 1, b: 2, c: 3, d: 4 };
14902 * var o2 = { a: 10, b: 20, c: 3, d: 40 };
14903 * R.eqProps('a', o1, o2); //=> false
14904 * R.eqProps('c', o1, o2); //=> true
14905 */
14906 var eqProps = _curry3(function eqProps(prop, obj1, obj2) {
14907 return _eq(obj1[prop], obj2[prop]);
14908 });
14909
14910 /**
14911 * Like `filter`, but passes additional parameters to the predicate function. The predicate
14912 * function is passed three arguments: *(value, index, list)*.
14913 *
14914 * @func
14915 * @memberOf R
14916 * @category List
14917 * @sig (a, i, [a] -> Boolean) -> [a] -> [a]
14918 * @param {Function} fn The function called per iteration.
14919 * @param {Array} list The collection to iterate over.
14920 * @return {Array} The new filtered array.
14921 * @example
14922 *
14923 * var lastTwo = function(val, idx, list) {
14924 * return list.length - idx <= 2;
14925 * };
14926 * R.filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9]
14927 */
14928 var filterIndexed = _curry2(_filterIndexed);
14929
14930 /**
14931 * Iterate over an input `list`, calling a provided function `fn` for each element in the
14932 * list.
14933 *
14934 * `fn` receives one argument: *(value)*.
14935 *
14936 * Note: `R.forEach` does not skip deleted or unassigned indices (sparse arrays), unlike
14937 * the native `Array.prototype.forEach` method. For more details on this behavior, see:
14938 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
14939 *
14940 * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original
14941 * array. In some libraries this function is named `each`.
14942 *
14943 * @func
14944 * @memberOf R
14945 * @category List
14946 * @sig (a -> *) -> [a] -> [a]
14947 * @param {Function} fn The function to invoke. Receives one argument, `value`.
14948 * @param {Array} list The list to iterate over.
14949 * @return {Array} The original list.
14950 * @example
14951 *
14952 * var printXPlusFive = function(x) { console.log(x + 5); };
14953 * R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]
14954 * //-> 6
14955 * //-> 7
14956 * //-> 8
14957 */
14958 var forEach = _curry2(_forEach);
14959
14960 /**
14961 * Like `forEach`, but but passes additional parameters to the predicate function.
14962 *
14963 * `fn` receives three arguments: *(value, index, list)*.
14964 *
14965 * Note: `R.forEachIndexed` does not skip deleted or unassigned indices (sparse arrays),
14966 * unlike the native `Array.prototype.forEach` method. For more details on this behavior,
14967 * see:
14968 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
14969 *
14970 * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original
14971 * array. In some libraries this function is named `each`.
14972 *
14973 * @func
14974 * @memberOf R
14975 * @category List
14976 * @sig (a, i, [a] -> ) -> [a] -> [a]
14977 * @param {Function} fn The function to invoke. Receives three arguments:
14978 * (`value`, `index`, `list`).
14979 * @param {Array} list The list to iterate over.
14980 * @return {Array} The original list.
14981 * @example
14982 *
14983 * // Note that having access to the original `list` allows for
14984 * // mutation. While you *can* do this, it's very un-functional behavior:
14985 * var plusFive = function(num, idx, list) { list[idx] = num + 5 };
14986 * R.forEachIndexed(plusFive, [1, 2, 3]); //=> [6, 7, 8]
14987 */
14988 // i can't bear not to return *something*
14989 var forEachIndexed = _curry2(function forEachIndexed(fn, list) {
14990 var idx = -1, len = list.length;
14991 while (++idx < len) {
14992 fn(list[idx], idx, list);
14993 }
14994 // i can't bear not to return *something*
14995 return list;
14996 });
14997
14998 /**
14999 * Creates a new object out of a list key-value pairs.
15000 *
15001 * @func
15002 * @memberOf R
15003 * @category List
15004 * @sig [[k,v]] -> {k: v}
15005 * @param {Array} pairs An array of two-element arrays that will be the keys and values of the output object.
15006 * @return {Object} The object made by pairing up `keys` and `values`.
15007 * @example
15008 *
15009 * R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}
15010 */
15011 var fromPairs = _curry1(function fromPairs(pairs) {
15012 var idx = -1, len = pairs.length, out = {};
15013 while (++idx < len) {
15014 if (_isArray(pairs[idx]) && pairs[idx].length) {
15015 out[pairs[idx][0]] = pairs[idx][1];
15016 }
15017 }
15018 return out;
15019 });
15020
15021 /**
15022 * Returns true if the first parameter is greater than the second.
15023 *
15024 * @func
15025 * @memberOf R
15026 * @category Math
15027 * @sig Number -> Number -> Boolean
15028 * @param {Number} a
15029 * @param {Number} b
15030 * @return {Boolean} a > b
15031 * @example
15032 *
15033 * R.gt(2, 6); //=> false
15034 * R.gt(2, 0); //=> true
15035 * R.gt(2, 2); //=> false
15036 * R.gt(R.__, 2)(10); //=> true
15037 * R.gt(2)(10); //=> false
15038 */
15039 var gt = _curry2(_gt);
15040
15041 /**
15042 * Returns true if the first parameter is greater than or equal to the second.
15043 *
15044 * @func
15045 * @memberOf R
15046 * @category Math
15047 * @sig Number -> Number -> Boolean
15048 * @param {Number} a
15049 * @param {Number} b
15050 * @return {Boolean} a >= b
15051 * @example
15052 *
15053 * R.gte(2, 6); //=> false
15054 * R.gte(2, 0); //=> true
15055 * R.gte(2, 2); //=> true
15056 * R.gte(R.__, 6)(2); //=> false
15057 * R.gte(2)(0); //=> true
15058 */
15059 var gte = _curry2(function gte(a, b) {
15060 return a >= b;
15061 });
15062
15063 /**
15064 * Returns whether or not an object has an own property with
15065 * the specified name
15066 *
15067 * @func
15068 * @memberOf R
15069 * @category Object
15070 * @sig s -> {s: x} -> Boolean
15071 * @param {String} prop The name of the property to check for.
15072 * @param {Object} obj The object to query.
15073 * @return {Boolean} Whether the property exists.
15074 * @example
15075 *
15076 * var hasName = R.has('name');
15077 * hasName({name: 'alice'}); //=> true
15078 * hasName({name: 'bob'}); //=> true
15079 * hasName({}); //=> false
15080 *
15081 * var point = {x: 0, y: 0};
15082 * var pointHas = R.has(R.__, point);
15083 * pointHas('x'); //=> true
15084 * pointHas('y'); //=> true
15085 * pointHas('z'); //=> false
15086 */
15087 var has = _curry2(_has);
15088
15089 /**
15090 * Returns whether or not an object or its prototype chain has
15091 * a property with the specified name
15092 *
15093 * @func
15094 * @memberOf R
15095 * @category Object
15096 * @sig s -> {s: x} -> Boolean
15097 * @param {String} prop The name of the property to check for.
15098 * @param {Object} obj The object to query.
15099 * @return {Boolean} Whether the property exists.
15100 * @example
15101 *
15102 * function Rectangle(width, height) {
15103 * this.width = width;
15104 * this.height = height;
15105 * }
15106 * Rectangle.prototype.area = function() {
15107 * return this.width * this.height;
15108 * };
15109 *
15110 * var square = new Rectangle(2, 2);
15111 * R.hasIn('width', square); //=> true
15112 * R.hasIn('area', square); //=> true
15113 */
15114 var hasIn = _curry2(function (prop, obj) {
15115 return prop in obj;
15116 });
15117
15118 /**
15119 * A function that does nothing but return the parameter supplied to it. Good as a default
15120 * or placeholder function.
15121 *
15122 * @func
15123 * @memberOf R
15124 * @category Function
15125 * @sig a -> a
15126 * @param {*} x The value to return.
15127 * @return {*} The input value, `x`.
15128 * @example
15129 *
15130 * R.identity(1); //=> 1
15131 *
15132 * var obj = {};
15133 * R.identity(obj) === obj; //=> true
15134 */
15135 var identity = _curry1(_identity);
15136
15137 /**
15138 * Creates a function that will process either the `onTrue` or the `onFalse` function depending
15139 * upon the result of the `condition` predicate.
15140 *
15141 * @func
15142 * @memberOf R
15143 * @category Logic
15144 * @sig (*... -> Boolean) -> (*... -> *) -> (*... -> *) -> (*... -> *)
15145 * @param {Function} condition A predicate function
15146 * @param {Function} onTrue A function to invoke when the `condition` evaluates to a truthy value.
15147 * @param {Function} onFalse A function to invoke when the `condition` evaluates to a falsy value.
15148 * @return {Function} A new unary function that will process either the `onTrue` or the `onFalse`
15149 * function depending upon the result of the `condition` predicate.
15150 * @example
15151 *
15152 * // Flatten all arrays in the list but leave other values alone.
15153 * var flattenArrays = R.map(R.ifElse(Array.isArray, R.flatten, R.identity));
15154 *
15155 * flattenArrays([[0], [[10], [8]], 1234, {}]); //=> [[0], [10, 8], 1234, {}]
15156 * flattenArrays([[[10], 123], [8, [10]], "hello"]); //=> [[10, 123], [8, 10], "hello"]
15157 */
15158 var ifElse = _curry3(function ifElse(condition, onTrue, onFalse) {
15159 return curryN(Math.max(condition.length, onTrue.length, onFalse.length), function _ifElse() {
15160 return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments);
15161 });
15162 });
15163
15164 /**
15165 * Increments its argument.
15166 *
15167 * @func
15168 * @memberOf R
15169 * @category Math
15170 * @sig Number -> Number
15171 * @param {Number} n
15172 * @return {Number}
15173 * @example
15174 *
15175 * R.inc(42); //=> 43
15176 */
15177 var inc = add(1);
15178
15179 /**
15180 * Returns the position of the first occurrence of an item in an array,
15181 * or -1 if the item is not included in the array.
15182 *
15183 * Has `Object.is` semantics: `NaN` is considered equal to `NaN`; `0` and `-0`
15184 * are not considered equal.
15185 *
15186 * @func
15187 * @memberOf R
15188 * @category List
15189 * @sig a -> [a] -> Number
15190 * @param {*} target The item to find.
15191 * @param {Array} list The array to search in.
15192 * @return {Number} the index of the target, or -1 if the target is not found.
15193 *
15194 * @example
15195 *
15196 * R.indexOf(3, [1,2,3,4]); //=> 2
15197 * R.indexOf(10, [1,2,3,4]); //=> -1
15198 */
15199 var indexOf = _curry2(function indexOf(target, list) {
15200 return _indexOf(list, target);
15201 });
15202
15203 /**
15204 * Inserts the sub-list into the list, at index `index`. _Note that this
15205 * is not destructive_: it returns a copy of the list with the changes.
15206 * <small>No lists have been harmed in the application of this function.</small>
15207 *
15208 * @func
15209 * @memberOf R
15210 * @category List
15211 * @sig Number -> [a] -> [a] -> [a]
15212 * @param {Number} index The position to insert the sub-list
15213 * @param {Array} elts The sub-list to insert into the Array
15214 * @param {Array} list The list to insert the sub-list into
15215 * @return {Array} A new Array with `elts` inserted starting at `index`.
15216 * @example
15217 *
15218 * R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4]
15219 */
15220 var insertAll = _curry3(function insertAll(idx, elts, list) {
15221 idx = idx < list.length && idx >= 0 ? idx : list.length;
15222 return _concat(_concat(_slice(list, 0, idx), elts), _slice(list, idx));
15223 });
15224
15225 /**
15226 * See if an object (`val`) is an instance of the supplied constructor.
15227 * This function will check up the inheritance chain, if any.
15228 *
15229 * @func
15230 * @memberOf R
15231 * @category Type
15232 * @sig (* -> {*}) -> a -> Boolean
15233 * @param {Object} ctor A constructor
15234 * @param {*} val The value to test
15235 * @return {Boolean}
15236 * @example
15237 *
15238 * R.is(Object, {}); //=> true
15239 * R.is(Number, 1); //=> true
15240 * R.is(Object, 1); //=> false
15241 * R.is(String, 's'); //=> true
15242 * R.is(String, new String('')); //=> true
15243 * R.is(Object, new String('')); //=> true
15244 * R.is(Object, 's'); //=> false
15245 * R.is(Number, {}); //=> false
15246 */
15247 var is = _curry2(function is(Ctor, val) {
15248 return val != null && val.constructor === Ctor || val instanceof Ctor;
15249 });
15250
15251 /**
15252 * Tests whether or not an object is similar to an array.
15253 *
15254 * @func
15255 * @memberOf R
15256 * @category Type
15257 * @category List
15258 * @sig * -> Boolean
15259 * @param {*} x The object to test.
15260 * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise.
15261 * @example
15262 *
15263 * R.isArrayLike([]); //=> true
15264 * R.isArrayLike(true); //=> false
15265 * R.isArrayLike({}); //=> false
15266 * R.isArrayLike({length: 10}); //=> false
15267 * R.isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true
15268 */
15269 var isArrayLike = _curry1(function isArrayLike(x) {
15270 if (_isArray(x)) {
15271 return true;
15272 }
15273 if (!x) {
15274 return false;
15275 }
15276 if (typeof x !== 'object') {
15277 return false;
15278 }
15279 if (x instanceof String) {
15280 return false;
15281 }
15282 if (x.nodeType === 1) {
15283 return !!x.length;
15284 }
15285 if (x.length === 0) {
15286 return true;
15287 }
15288 if (x.length > 0) {
15289 return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1);
15290 }
15291 return false;
15292 });
15293
15294 /**
15295 * Reports whether the list has zero elements.
15296 *
15297 * @func
15298 * @memberOf R
15299 * @category Logic
15300 * @sig [a] -> Boolean
15301 * @param {Array} list
15302 * @return {Boolean}
15303 * @example
15304 *
15305 * R.isEmpty([1, 2, 3]); //=> false
15306 * R.isEmpty([]); //=> true
15307 * R.isEmpty(''); //=> true
15308 * R.isEmpty(null); //=> false
15309 */
15310 var isEmpty = _curry1(function isEmpty(list) {
15311 return Object(list).length === 0;
15312 });
15313
15314 /**
15315 * Returns `true` if the input value is `NaN`.
15316 *
15317 * Equivalent to ES6's [`Number.isNaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN).
15318 *
15319 * @deprecated since v0.14.0
15320 * @func
15321 * @memberOf R
15322 * @category Math
15323 * @sig * -> Boolean
15324 * @param {*} x
15325 * @return {Boolean}
15326 * @example
15327 *
15328 * R.isNaN(NaN); //=> true
15329 * R.isNaN(undefined); //=> false
15330 * R.isNaN({}); //=> false
15331 */
15332 var isNaN = _curry1(function isNaN(x) {
15333 return typeof x === 'number' && x !== x;
15334 });
15335
15336 /**
15337 * Checks if the input value is `null` or `undefined`.
15338 *
15339 * @func
15340 * @memberOf R
15341 * @category Type
15342 * @sig * -> Boolean
15343 * @param {*} x The value to test.
15344 * @return {Boolean} `true` if `x` is `undefined` or `null`, otherwise `false`.
15345 * @example
15346 *
15347 * R.isNil(null); //=> true
15348 * R.isNil(undefined); //=> true
15349 * R.isNil(0); //=> false
15350 * R.isNil([]); //=> false
15351 */
15352 var isNil = _curry1(function isNil(x) {
15353 return x == null;
15354 });
15355
15356 /**
15357 * Returns `true` if all elements are unique, otherwise `false`.
15358 *
15359 * Has `Object.is` semantics: `NaN` is considered equal to `NaN`; `0` and `-0`
15360 * are not considered equal.
15361 *
15362 * @func
15363 * @memberOf R
15364 * @category List
15365 * @sig [a] -> Boolean
15366 * @param {Array} list The array to consider.
15367 * @return {Boolean} `true` if all elements are unique, else `false`.
15368 * @example
15369 *
15370 * R.isSet(['1', 1]); //=> true
15371 * R.isSet([1, 1]); //=> false
15372 * R.isSet([{}, {}]); //=> true
15373 */
15374 var isSet = _curry1(function isSet(list) {
15375 var len = list.length;
15376 var idx = -1;
15377 while (++idx < len) {
15378 if (_indexOf(list, list[idx], idx + 1) >= 0) {
15379 return false;
15380 }
15381 }
15382 return true;
15383 });
15384
15385 /**
15386 * Returns a list containing the names of all the
15387 * properties of the supplied object, including prototype properties.
15388 * Note that the order of the output array is not guaranteed to be
15389 * consistent across different JS platforms.
15390 *
15391 * @func
15392 * @memberOf R
15393 * @category Object
15394 * @sig {k: v} -> [k]
15395 * @param {Object} obj The object to extract properties from
15396 * @return {Array} An array of the object's own and prototype properties.
15397 * @example
15398 *
15399 * var F = function() { this.x = 'X'; };
15400 * F.prototype.y = 'Y';
15401 * var f = new F();
15402 * R.keysIn(f); //=> ['x', 'y']
15403 */
15404 var keysIn = _curry1(function keysIn(obj) {
15405 var prop, ks = [];
15406 for (prop in obj) {
15407 ks[ks.length] = prop;
15408 }
15409 return ks;
15410 });
15411
15412 /**
15413 * Returns the position of the last occurrence of an item in
15414 * an array, or -1 if the item is not included in the array.
15415 *
15416 * Has `Object.is` semantics: `NaN` is considered equal to `NaN`; `0` and `-0`
15417 * are not considered equal.
15418 *
15419 * @func
15420 * @memberOf R
15421 * @category List
15422 * @sig a -> [a] -> Number
15423 * @param {*} target The item to find.
15424 * @param {Array} list The array to search in.
15425 * @return {Number} the index of the target, or -1 if the target is not found.
15426 *
15427 * @example
15428 *
15429 * R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6
15430 * R.lastIndexOf(10, [1,2,3,4]); //=> -1
15431 */
15432 var lastIndexOf = _curry2(function lastIndexOf(target, list) {
15433 return _lastIndexOf(list, target);
15434 });
15435
15436 /**
15437 * Returns the number of elements in the array by returning `list.length`.
15438 *
15439 * @func
15440 * @memberOf R
15441 * @category List
15442 * @sig [a] -> Number
15443 * @param {Array} list The array to inspect.
15444 * @return {Number} The length of the array.
15445 * @example
15446 *
15447 * R.length([]); //=> 0
15448 * R.length([1, 2, 3]); //=> 3
15449 */
15450 var length = _curry1(function length(list) {
15451 return list != null && is(Number, list.length) ? list.length : NaN;
15452 });
15453
15454 /**
15455 * Creates a lens. Supply a function to `get` values from inside an object, and a `set`
15456 * function to change values on an object. (n.b.: This can, and should, be done without
15457 * mutating the original object!) The lens is a function wrapped around the input `get`
15458 * function, with the `set` function attached as a property on the wrapper. A `map`
15459 * function is also attached to the returned function that takes a function to operate
15460 * on the specified (`get`) property, which is then `set` before returning. The attached
15461 * `set` and `map` functions are curried.
15462 *
15463 * @func
15464 * @memberOf R
15465 * @category Object
15466 * @sig (k -> v) -> (v -> a -> *) -> (a -> b)
15467 * @param {Function} get A function that gets a value by property name
15468 * @param {Function} set A function that sets a value by property name
15469 * @return {Function} the returned function has `set` and `map` properties that are
15470 * also curried functions.
15471 * @example
15472 *
15473 * var headLens = R.lens(
15474 * function get(arr) { return arr[0]; },
15475 * function set(val, arr) { return [val].concat(arr.slice(1)); }
15476 * );
15477 * headLens([10, 20, 30, 40]); //=> 10
15478 * headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40]
15479 * headLens.map(function(x) { return x + 1; }, [10, 20, 30, 40]); //=> [11, 20, 30, 40]
15480 *
15481 * var phraseLens = R.lens(
15482 * function get(obj) { return obj.phrase; },
15483 * function set(val, obj) {
15484 * var out = R.clone(obj);
15485 * out.phrase = val;
15486 * return out;
15487 * }
15488 * );
15489 * var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'};
15490 * var obj2 = { phrase: "What's all this, then?"};
15491 * phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!'
15492 * phraseLens(obj2); // => "What's all this, then?"
15493 * phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'}
15494 * phraseLens.map(R.toUpper, obj2); //=> { phrase: "WHAT'S ALL THIS, THEN?"}
15495 */
15496 var lens = _curry2(function lens(get, set) {
15497 var lns = function (a) {
15498 return get(a);
15499 };
15500 lns.set = _curry2(set);
15501 lns.map = _curry2(function (fn, a) {
15502 return set(fn(get(a)), a);
15503 });
15504 return lns;
15505 });
15506
15507 /**
15508 * Returns a lens associated with the provided object.
15509 *
15510 * @func
15511 * @memberOf R
15512 * @category Object
15513 * @sig ({} -> v) -> (v -> a -> *) -> {} -> (a -> b)
15514 * @see R.lens
15515 * @param {Function} get A function that gets a value by property name
15516 * @param {Function} set A function that sets a value by property name
15517 * @param {Object} the actual object of interest
15518 * @return {Function} the returned function has `set` and `map` properties that are
15519 * also curried functions.
15520 * @example
15521 *
15522 * var xo = {x: 1};
15523 * var xoLens = R.lensOn(function get(o) { return o.x; },
15524 * function set(v) { return {x: v}; },
15525 * xo);
15526 * xoLens(); //=> 1
15527 * xoLens.set(1000); //=> {x: 1000}
15528 * xoLens.map(R.add(1)); //=> {x: 2}
15529 */
15530 var lensOn = _curry3(function lensOn(get, set, obj) {
15531 var lns = function () {
15532 return get(obj);
15533 };
15534 lns.set = set;
15535 lns.map = function (fn) {
15536 return set(fn(get(obj)));
15537 };
15538 return lns;
15539 });
15540
15541 /**
15542 * Returns true if the first parameter is less than the second.
15543 *
15544 * @func
15545 * @memberOf R
15546 * @category Math
15547 * @sig Number -> Number -> Boolean
15548 * @param {Number} a
15549 * @param {Number} b
15550 * @return {Boolean} a < b
15551 * @example
15552 *
15553 * R.lt(2, 6); //=> true
15554 * R.lt(2, 0); //=> false
15555 * R.lt(2, 2); //=> false
15556 * R.lt(5)(10); //=> true
15557 * R.lt(R.__, 5)(10); //=> false // right-sectioned currying
15558 */
15559 var lt = _curry2(_lt);
15560
15561 /**
15562 * Returns true if the first parameter is less than or equal to the second.
15563 *
15564 * @func
15565 * @memberOf R
15566 * @category Math
15567 * @sig Number -> Number -> Boolean
15568 * @param {Number} a
15569 * @param {Number} b
15570 * @return {Boolean} a <= b
15571 * @example
15572 *
15573 * R.lte(2, 6); //=> true
15574 * R.lte(2, 0); //=> false
15575 * R.lte(2, 2); //=> true
15576 * R.lte(R.__, 2)(1); //=> true
15577 * R.lte(2)(10); //=> true
15578 */
15579 var lte = _curry2(function lte(a, b) {
15580 return a <= b;
15581 });
15582
15583 /**
15584 * The mapAccum function behaves like a combination of map and reduce; it applies a
15585 * function to each element of a list, passing an accumulating parameter from left to
15586 * right, and returning a final value of this accumulator together with the new list.
15587 *
15588 * The iterator function receives two arguments, *acc* and *value*, and should return
15589 * a tuple *[acc, value]*.
15590 *
15591 * @func
15592 * @memberOf R
15593 * @category List
15594 * @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
15595 * @param {Function} fn The function to be called on every element of the input `list`.
15596 * @param {*} acc The accumulator value.
15597 * @param {Array} list The list to iterate over.
15598 * @return {*} The final, accumulated value.
15599 * @example
15600 *
15601 * var digits = ['1', '2', '3', '4'];
15602 * var append = function(a, b) {
15603 * return [a + b, a + b];
15604 * }
15605 *
15606 * R.mapAccum(append, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']]
15607 */
15608 var mapAccum = _curry3(function mapAccum(fn, acc, list) {
15609 var idx = -1, len = list.length, result = [], tuple = [acc];
15610 while (++idx < len) {
15611 tuple = fn(tuple[0], list[idx]);
15612 result[idx] = tuple[1];
15613 }
15614 return [
15615 tuple[0],
15616 result
15617 ];
15618 });
15619
15620 /**
15621 * The mapAccumRight function behaves like a combination of map and reduce; it applies a
15622 * function to each element of a list, passing an accumulating parameter from right
15623 * to left, and returning a final value of this accumulator together with the new list.
15624 *
15625 * Similar to `mapAccum`, except moves through the input list from the right to the
15626 * left.
15627 *
15628 * The iterator function receives two arguments, *acc* and *value*, and should return
15629 * a tuple *[acc, value]*.
15630 *
15631 * @func
15632 * @memberOf R
15633 * @category List
15634 * @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
15635 * @param {Function} fn The function to be called on every element of the input `list`.
15636 * @param {*} acc The accumulator value.
15637 * @param {Array} list The list to iterate over.
15638 * @return {*} The final, accumulated value.
15639 * @example
15640 *
15641 * var digits = ['1', '2', '3', '4'];
15642 * var append = function(a, b) {
15643 * return [a + b, a + b];
15644 * }
15645 *
15646 * R.mapAccumRight(append, 0, digits); //=> ['04321', ['04321', '0432', '043', '04']]
15647 */
15648 var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) {
15649 var idx = list.length, result = [], tuple = [acc];
15650 while (--idx >= 0) {
15651 tuple = fn(tuple[0], list[idx]);
15652 result[idx] = tuple[1];
15653 }
15654 return [
15655 tuple[0],
15656 result
15657 ];
15658 });
15659
15660 /**
15661 * Like `map`, but but passes additional parameters to the mapping function.
15662 * `fn` receives three arguments: *(value, index, list)*.
15663 *
15664 * Note: `R.mapIndexed` does not skip deleted or unassigned indices (sparse arrays), unlike
15665 * the native `Array.prototype.map` method. For more details on this behavior, see:
15666 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
15667 *
15668 * @func
15669 * @memberOf R
15670 * @category List
15671 * @sig (a,i,[b] -> b) -> [a] -> [b]
15672 * @param {Function} fn The function to be called on every element of the input `list`.
15673 * @param {Array} list The list to be iterated over.
15674 * @return {Array} The new list.
15675 * @example
15676 *
15677 * var squareEnds = function(elt, idx, list) {
15678 * if (idx === 0 || idx === list.length - 1) {
15679 * return elt * elt;
15680 * }
15681 * return elt;
15682 * };
15683 *
15684 * R.mapIndexed(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81]
15685 */
15686 var mapIndexed = _curry2(function mapIndexed(fn, list) {
15687 var idx = -1, len = list.length, result = [];
15688 while (++idx < len) {
15689 result[idx] = fn(list[idx], idx, list);
15690 }
15691 return result;
15692 });
15693
15694 /**
15695 * mathMod behaves like the modulo operator should mathematically, unlike the `%`
15696 * operator (and by extension, R.modulo). So while "-17 % 5" is -2,
15697 * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN
15698 * when the modulus is zero or negative.
15699 *
15700 * @func
15701 * @memberOf R
15702 * @category Math
15703 * @sig Number -> Number -> Number
15704 * @param {Number} m The dividend.
15705 * @param {Number} p the modulus.
15706 * @return {Number} The result of `b mod a`.
15707 * @see R.moduloBy
15708 * @example
15709 *
15710 * R.mathMod(-17, 5); //=> 3
15711 * R.mathMod(17, 5); //=> 2
15712 * R.mathMod(17, -5); //=> NaN
15713 * R.mathMod(17, 0); //=> NaN
15714 * R.mathMod(17.2, 5); //=> NaN
15715 * R.mathMod(17, 5.3); //=> NaN
15716 *
15717 * var clock = R.mathMod(R.__, 12);
15718 * clock(15); //=> 3
15719 * clock(24); //=> 0
15720 *
15721 * var seventeenMod = R.mathMod(17);
15722 * seventeenMod(3); //=> 2
15723 * seventeenMod(4); //=> 1
15724 * seventeenMod(10); //=> 7
15725 */
15726 var mathMod = _curry2(function mathMod(m, p) {
15727 if (!_isInteger(m)) {
15728 return NaN;
15729 }
15730 if (!_isInteger(p) || p < 1) {
15731 return NaN;
15732 }
15733 return (m % p + p) % p;
15734 });
15735
15736 /**
15737 * Determines the largest of a list of items as determined by pairwise comparisons from the supplied comparator.
15738 * Note that this will return undefined if supplied an empty list.
15739 *
15740 * @func
15741 * @memberOf R
15742 * @category Math
15743 * @sig (a -> Number) -> [a] -> a
15744 * @param {Function} keyFn A comparator function for elements in the list
15745 * @param {Array} list A list of comparable elements
15746 * @return {*} The greatest element in the list. `undefined` if the list is empty.
15747 * @see R.max
15748 * @example
15749 *
15750 * function cmp(obj) { return obj.x; }
15751 * var a = {x: 1}, b = {x: 2}, c = {x: 3};
15752 * R.maxBy(cmp, [a, b, c]); //=> {x: 3}
15753 */
15754 var maxBy = _curry2(_createMaxMinBy(_gt));
15755
15756 /**
15757 * Determines the smallest of a list of items as determined by pairwise comparisons from the supplied comparator
15758 * Note that this will return undefined if supplied an empty list.
15759 *
15760 * @func
15761 * @memberOf R
15762 * @category Math
15763 * @sig (a -> Number) -> [a] -> a
15764 * @param {Function} keyFn A comparator function for elements in the list
15765 * @param {Array} list A list of comparable elements
15766 * @see R.min
15767 * @return {*} The greatest element in the list. `undefined` if the list is empty.
15768 * @example
15769 *
15770 * function cmp(obj) { return obj.x; }
15771 * var a = {x: 1}, b = {x: 2}, c = {x: 3};
15772 * R.minBy(cmp, [a, b, c]); //=> {x: 1}
15773 */
15774 var minBy = _curry2(_createMaxMinBy(_lt));
15775
15776 /**
15777 * Divides the second parameter by the first and returns the remainder.
15778 * Note that this functions preserves the JavaScript-style behavior for
15779 * modulo. For mathematical modulo see `mathMod`
15780 *
15781 * @func
15782 * @memberOf R
15783 * @category Math
15784 * @sig Number -> Number -> Number
15785 * @param {Number} a The value to the divide.
15786 * @param {Number} b The pseudo-modulus
15787 * @return {Number} The result of `b % a`.
15788 * @see R.mathMod
15789 * @example
15790 *
15791 * R.modulo(17, 3); //=> 2
15792 * // JS behavior:
15793 * R.modulo(-17, 3); //=> -2
15794 * R.modulo(17, -3); //=> 2
15795 *
15796 * var isOdd = R.modulo(R.__, 2);
15797 * isOdd(42); //=> 0
15798 * isOdd(21); //=> 1
15799 */
15800 var modulo = _curry2(function modulo(a, b) {
15801 return a % b;
15802 });
15803
15804 /**
15805 * Multiplies two numbers. Equivalent to `a * b` but curried.
15806 *
15807 * @func
15808 * @memberOf R
15809 * @category Math
15810 * @sig Number -> Number -> Number
15811 * @param {Number} a The first value.
15812 * @param {Number} b The second value.
15813 * @return {Number} The result of `a * b`.
15814 * @example
15815 *
15816 * var double = R.multiply(2);
15817 * var triple = R.multiply(3);
15818 * double(3); //=> 6
15819 * triple(4); //=> 12
15820 * R.multiply(2, 5); //=> 10
15821 */
15822 var multiply = _curry2(_multiply);
15823
15824 /**
15825 * Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
15826 * parameters. Any extraneous parameters will not be passed to the supplied function.
15827 *
15828 * @func
15829 * @memberOf R
15830 * @category Function
15831 * @sig Number -> (* -> a) -> (* -> a)
15832 * @param {Number} n The desired arity of the new function.
15833 * @param {Function} fn The function to wrap.
15834 * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
15835 * arity `n`.
15836 * @example
15837 *
15838 * var takesTwoArgs = function(a, b) {
15839 * return [a, b];
15840 * };
15841 * takesTwoArgs.length; //=> 2
15842 * takesTwoArgs(1, 2); //=> [1, 2]
15843 *
15844 * var takesOneArg = R.nAry(1, takesTwoArgs);
15845 * takesOneArg.length; //=> 1
15846 * // Only `n` arguments are passed to the wrapped function
15847 * takesOneArg(1, 2); //=> [1, undefined]
15848 */
15849 var nAry = _curry2(function (n, fn) {
15850 switch (n) {
15851 case 0:
15852 return function () {
15853 return fn.call(this);
15854 };
15855 case 1:
15856 return function (a0) {
15857 return fn.call(this, a0);
15858 };
15859 case 2:
15860 return function (a0, a1) {
15861 return fn.call(this, a0, a1);
15862 };
15863 case 3:
15864 return function (a0, a1, a2) {
15865 return fn.call(this, a0, a1, a2);
15866 };
15867 case 4:
15868 return function (a0, a1, a2, a3) {
15869 return fn.call(this, a0, a1, a2, a3);
15870 };
15871 case 5:
15872 return function (a0, a1, a2, a3, a4) {
15873 return fn.call(this, a0, a1, a2, a3, a4);
15874 };
15875 case 6:
15876 return function (a0, a1, a2, a3, a4, a5) {
15877 return fn.call(this, a0, a1, a2, a3, a4, a5);
15878 };
15879 case 7:
15880 return function (a0, a1, a2, a3, a4, a5, a6) {
15881 return fn.call(this, a0, a1, a2, a3, a4, a5, a6);
15882 };
15883 case 8:
15884 return function (a0, a1, a2, a3, a4, a5, a6, a7) {
15885 return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);
15886 };
15887 case 9:
15888 return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
15889 return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);
15890 };
15891 case 10:
15892 return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
15893 return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
15894 };
15895 default:
15896 throw new Error('First argument to nAry must be a non-negative integer no greater than ten');
15897 }
15898 });
15899
15900 /**
15901 * Negates its argument.
15902 *
15903 * @func
15904 * @memberOf R
15905 * @category Math
15906 * @sig Number -> Number
15907 * @param {Number} n
15908 * @return {Number}
15909 * @example
15910 *
15911 * R.negate(42); //=> -42
15912 */
15913 var negate = _curry1(function negate(n) {
15914 return -n;
15915 });
15916
15917 /**
15918 * A function that returns the `!` of its argument. It will return `true` when
15919 * passed false-y value, and `false` when passed a truth-y one.
15920 *
15921 * @func
15922 * @memberOf R
15923 * @category Logic
15924 * @sig * -> Boolean
15925 * @param {*} a any value
15926 * @return {Boolean} the logical inverse of passed argument.
15927 * @see complement
15928 * @example
15929 *
15930 * R.not(true); //=> false
15931 * R.not(false); //=> true
15932 * R.not(0); => true
15933 * R.not(1); => false
15934 */
15935 var not = _curry1(function not(a) {
15936 return !a;
15937 });
15938
15939 /**
15940 * Returns the nth element in a list.
15941 * If n is negative the element at index length + n is returned.
15942 *
15943 * @func
15944 * @memberOf R
15945 * @category List
15946 * @sig Number -> [a] -> a
15947 * @param {Number} idx
15948 * @param {Array} list
15949 * @return {*} The nth element of the list.
15950 * @example
15951 *
15952 * var list = ['foo', 'bar', 'baz', 'quux'];
15953 * R.nth(1, list); //=> 'bar'
15954 * R.nth(-1, list); //=> 'quux'
15955 * R.nth(-99, list); //=> undefined
15956 */
15957 var nth = _curry2(_nth);
15958
15959 /**
15960 * Returns a function which returns its nth argument.
15961 *
15962 * @func
15963 * @memberOf R
15964 * @category Function
15965 * @sig Number -> *... -> *
15966 * @param {Number} n
15967 * @return {Function}
15968 * @example
15969 *
15970 * R.nthArg(1)('a', 'b', 'c'); //=> 'b'
15971 * R.nthArg(-1)('a', 'b', 'c'); //=> 'c'
15972 */
15973 var nthArg = _curry1(function nthArg(n) {
15974 return function () {
15975 return _nth(n, arguments);
15976 };
15977 });
15978
15979 /**
15980 * Returns the nth character of the given string.
15981 *
15982 * @func
15983 * @memberOf R
15984 * @category String
15985 * @sig Number -> String -> String
15986 * @param {Number} n
15987 * @param {String} str
15988 * @return {String}
15989 * @example
15990 *
15991 * R.nthChar(2, 'Ramda'); //=> 'm'
15992 * R.nthChar(-2, 'Ramda'); //=> 'd'
15993 */
15994 var nthChar = _curry2(function nthChar(n, str) {
15995 return str.charAt(n < 0 ? str.length + n : n);
15996 });
15997
15998 /**
15999 * Returns the character code of the nth character of the given string.
16000 *
16001 * @func
16002 * @memberOf R
16003 * @category String
16004 * @sig Number -> String -> Number
16005 * @param {Number} n
16006 * @param {String} str
16007 * @return {Number}
16008 * @example
16009 *
16010 * R.nthCharCode(2, 'Ramda'); //=> 'm'.charCodeAt(0)
16011 * R.nthCharCode(-2, 'Ramda'); //=> 'd'.charCodeAt(0)
16012 */
16013 var nthCharCode = _curry2(function nthCharCode(n, str) {
16014 return str.charCodeAt(n < 0 ? str.length + n : n);
16015 });
16016
16017 /**
16018 * Returns a singleton array containing the value provided.
16019 *
16020 * Note this `of` is different from the ES6 `of`; See
16021 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
16022 *
16023 * @func
16024 * @memberOf R
16025 * @category Function
16026 * @sig a -> [a]
16027 * @param {*} x any value
16028 * @return {Array} An array wrapping `x`.
16029 * @example
16030 *
16031 * R.of(null); //=> [null]
16032 * R.of([42]); //=> [[42]]
16033 */
16034 var of = _curry1(function of(x) {
16035 return [x];
16036 });
16037
16038 /**
16039 * Returns a partial copy of an object omitting the keys specified.
16040 *
16041 * @func
16042 * @memberOf R
16043 * @category Object
16044 * @sig [String] -> {String: *} -> {String: *}
16045 * @param {Array} names an array of String property names to omit from the new object
16046 * @param {Object} obj The object to copy from
16047 * @return {Object} A new object with properties from `names` not on it.
16048 * @example
16049 *
16050 * R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
16051 */
16052 var omit = _curry2(function omit(names, obj) {
16053 var result = {};
16054 for (var prop in obj) {
16055 if (_indexOf(names, prop) < 0) {
16056 result[prop] = obj[prop];
16057 }
16058 }
16059 return result;
16060 });
16061
16062 /**
16063 * Accepts a function `fn` and returns a function that guards invocation of `fn` such that
16064 * `fn` can only ever be called once, no matter how many times the returned function is
16065 * invoked.
16066 *
16067 * @func
16068 * @memberOf R
16069 * @category Function
16070 * @sig (a... -> b) -> (a... -> b)
16071 * @param {Function} fn The function to wrap in a call-only-once wrapper.
16072 * @return {Function} The wrapped function.
16073 * @example
16074 *
16075 * var addOneOnce = R.once(function(x){ return x + 1; });
16076 * addOneOnce(10); //=> 11
16077 * addOneOnce(addOneOnce(50)); //=> 11
16078 */
16079 var once = _curry1(function once(fn) {
16080 var called = false, result;
16081 return function () {
16082 if (called) {
16083 return result;
16084 }
16085 called = true;
16086 result = fn.apply(this, arguments);
16087 return result;
16088 };
16089 });
16090
16091 /**
16092 * Retrieve the value at a given path.
16093 *
16094 * @func
16095 * @memberOf R
16096 * @category Object
16097 * @sig [String] -> {*} -> *
16098 * @param {Array} path The path to use.
16099 * @return {*} The data at `path`.
16100 * @example
16101 *
16102 * R.path(['a', 'b'], {a: {b: 2}}); //=> 2
16103 */
16104 var path = _curry2(_path);
16105
16106 /**
16107 * Determines whether a nested path on an object has a specific value.
16108 * Most likely used to filter a list.
16109 *
16110 * Has `Object.is` semantics: `NaN` is considered equal to `NaN`; `0` and `-0`
16111 * are not considered equal.
16112 *
16113 * @func
16114 * @memberOf R
16115 * @category Relation
16116 * @sig [String] -> * -> {String: *} -> Boolean
16117 * @param {Array} path The path of the nested property to use
16118 * @param {*} val The value to compare the nested property with
16119 * @param {Object} obj The object to check the nested property in
16120 * @return {Boolean} `true` if the value equals the nested object property,
16121 * `false` otherwise.
16122 * @example
16123 *
16124 * var user1 = { address: { zipCode: 90210 } };
16125 * var user2 = { address: { zipCode: 55555 } };
16126 * var user3 = { name: 'Bob' };
16127 * var users = [ user1, user2, user3 ];
16128 * var isFamous = R.pathEq(['address', 'zipCode'], 90210);
16129 * R.filter(isFamous, users); //=> [ user1 ]
16130 */
16131 var pathEq = _curry3(function pathEq(path, val, obj) {
16132 return _eq(_path(path, obj), val);
16133 });
16134
16135 /**
16136 * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the
16137 * property is ignored.
16138 *
16139 * @func
16140 * @memberOf R
16141 * @category Object
16142 * @sig [String] -> {String: *} -> {String: *}
16143 * @param {Array} names an array of String property names to copy onto a new object
16144 * @param {Object} obj The object to copy from
16145 * @return {Object} A new object with only properties from `names` on it.
16146 * @example
16147 *
16148 * R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
16149 * R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}
16150 */
16151 var pick = _curry2(function pick(names, obj) {
16152 var result = {};
16153 for (var prop in obj) {
16154 if (_indexOf(names, prop) >= 0) {
16155 result[prop] = obj[prop];
16156 }
16157 }
16158 return result;
16159 });
16160
16161 /**
16162 * Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist.
16163 *
16164 * @func
16165 * @memberOf R
16166 * @category Object
16167 * @sig [k] -> {k: v} -> {k: v}
16168 * @param {Array} names an array of String property names to copy onto a new object
16169 * @param {Object} obj The object to copy from
16170 * @return {Object} A new object with only properties from `names` on it.
16171 * @see R.pick
16172 * @example
16173 *
16174 * R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
16175 * R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined}
16176 */
16177 var pickAll = _curry2(function pickAll(names, obj) {
16178 var result = {};
16179 var idx = -1;
16180 var len = names.length;
16181 while (++idx < len) {
16182 var name = names[idx];
16183 result[name] = obj[name];
16184 }
16185 return result;
16186 });
16187
16188 /**
16189 * Returns a partial copy of an object containing only the keys that
16190 * satisfy the supplied predicate.
16191 *
16192 * @func
16193 * @memberOf R
16194 * @category Object
16195 * @sig (v, k -> Boolean) -> {k: v} -> {k: v}
16196 * @param {Function} pred A predicate to determine whether or not a key
16197 * should be included on the output object.
16198 * @param {Object} obj The object to copy from
16199 * @return {Object} A new object with only properties that satisfy `pred`
16200 * on it.
16201 * @see R.pick
16202 * @example
16203 *
16204 * var isUpperCase = function(val, key) { return key.toUpperCase() === key; }
16205 * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
16206 */
16207 var pickBy = _curry2(function pickBy(test, obj) {
16208 var result = {};
16209 for (var prop in obj) {
16210 if (test(obj[prop], prop, obj)) {
16211 result[prop] = obj[prop];
16212 }
16213 }
16214 return result;
16215 });
16216
16217 /**
16218 * Returns a new list with the given element at the front, followed by the contents of the
16219 * list.
16220 *
16221 * @func
16222 * @memberOf R
16223 * @category List
16224 * @sig a -> [a] -> [a]
16225 * @param {*} el The item to add to the head of the output list.
16226 * @param {Array} list The array to add to the tail of the output list.
16227 * @return {Array} A new array.
16228 * @example
16229 *
16230 * R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']
16231 */
16232 var prepend = _curry2(_prepend);
16233
16234 /**
16235 * Returns a function that when supplied an object returns the indicated property of that object, if it exists.
16236 *
16237 * @func
16238 * @memberOf R
16239 * @category Object
16240 * @sig s -> {s: a} -> a
16241 * @param {String} p The property name
16242 * @param {Object} obj The object to query
16243 * @return {*} The value at `obj.p`.
16244 * @example
16245 *
16246 * R.prop('x', {x: 100}); //=> 100
16247 * R.prop('x', {}); //=> undefined
16248 */
16249 var prop = _curry2(function prop(p, obj) {
16250 return obj[p];
16251 });
16252
16253 /**
16254 * Determines whether the given property of an object has a specific value.
16255 * Most likely used to filter a list.
16256 *
16257 * Has `Object.is` semantics: `NaN` is considered equal to `NaN`; `0` and `-0`
16258 * are not considered equal.
16259 *
16260 * @func
16261 * @memberOf R
16262 * @category Relation
16263 * @sig k -> v -> {k: v} -> Boolean
16264 * @param {Number|String} name The property name (or index) to use.
16265 * @param {*} val The value to compare the property with.
16266 * @return {Boolean} `true` if the properties are equal, `false` otherwise.
16267 * @example
16268 *
16269 * var abby = {name: 'Abby', age: 7, hair: 'blond'};
16270 * var fred = {name: 'Fred', age: 12, hair: 'brown'};
16271 * var rusty = {name: 'Rusty', age: 10, hair: 'brown'};
16272 * var alois = {name: 'Alois', age: 15, disposition: 'surly'};
16273 * var kids = [abby, fred, rusty, alois];
16274 * var hasBrownHair = R.propEq('hair', 'brown');
16275 * R.filter(hasBrownHair, kids); //=> [fred, rusty]
16276 */
16277 var propEq = _curry3(function propEq(name, val, obj) {
16278 return _eq(obj[name], val);
16279 });
16280
16281 /**
16282 * If the given, non-null object has an own property with the specified name,
16283 * returns the value of that property.
16284 * Otherwise returns the provided default value.
16285 *
16286 * @func
16287 * @memberOf R
16288 * @category Object
16289 * @sig a -> String -> Object -> a
16290 * @param {*} val The default value.
16291 * @param {String} p The name of the property to return.
16292 * @param {Object} obj The object to query.
16293 * @return {*} The value of given property of the supplied object or the default value.
16294 * @example
16295 *
16296 * var alice = {
16297 * name: 'ALICE',
16298 * age: 101
16299 * };
16300 * var favorite = R.prop('favoriteLibrary');
16301 * var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary');
16302 *
16303 * favorite(alice); //=> undefined
16304 * favoriteWithDefault(alice); //=> 'Ramda'
16305 */
16306 var propOr = _curry3(function propOr(val, p, obj) {
16307 return _has(p, obj) ? obj[p] : val;
16308 });
16309
16310 /**
16311 * Acts as multiple `get`: array of keys in, array of values out. Preserves order.
16312 *
16313 * @func
16314 * @memberOf R
16315 * @category Object
16316 * @sig [k] -> {k: v} -> [v]
16317 * @param {Array} ps The property names to fetch
16318 * @param {Object} obj The object to query
16319 * @return {Array} The corresponding values or partially applied function.
16320 * @example
16321 *
16322 * R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2]
16323 * R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2]
16324 *
16325 * var fullName = R.compose(R.join(' '), R.props(['first', 'last']));
16326 * fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth'
16327 */
16328 var props = _curry2(function props(ps, obj) {
16329 var len = ps.length;
16330 var out = [];
16331 var idx = -1;
16332 while (++idx < len) {
16333 out[idx] = obj[ps[idx]];
16334 }
16335 return out;
16336 });
16337
16338 /**
16339 * Returns a list of numbers from `from` (inclusive) to `to`
16340 * (exclusive).
16341 *
16342 * @func
16343 * @memberOf R
16344 * @category List
16345 * @sig Number -> Number -> [Number]
16346 * @param {Number} from The first number in the list.
16347 * @param {Number} to One more than the last number in the list.
16348 * @return {Array} The list of numbers in tthe set `[a, b)`.
16349 * @example
16350 *
16351 * R.range(1, 5); //=> [1, 2, 3, 4]
16352 * R.range(50, 53); //=> [50, 51, 52]
16353 */
16354 var range = _curry2(function range(from, to) {
16355 var result = [];
16356 var n = from;
16357 while (n < to) {
16358 result[result.length] = n;
16359 n += 1;
16360 }
16361 return result;
16362 });
16363
16364 /**
16365 * Like `reduce`, but passes additional parameters to the predicate function.
16366 *
16367 * The iterator function receives four values: *(acc, value, index, list)*
16368 *
16369 * Note: `R.reduceIndexed` does not skip deleted or unassigned indices (sparse arrays),
16370 * unlike the native `Array.prototype.reduce` method. For more details on this behavior,
16371 * see:
16372 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
16373 *
16374 * @func
16375 * @memberOf R
16376 * @category List
16377 * @sig (a,b,i,[b] -> a) -> a -> [b] -> a
16378 * @param {Function} fn The iterator function. Receives four values: the accumulator, the
16379 * current element from `list`, that element's index, and the entire `list` itself.
16380 * @param {*} acc The accumulator value.
16381 * @param {Array} list The list to iterate over.
16382 * @return {*} The final, accumulated value.
16383 * @example
16384 *
16385 * var letters = ['a', 'b', 'c'];
16386 * var objectify = function(accObject, elem, idx, list) {
16387 * accObject[elem] = idx;
16388 * return accObject;
16389 * };
16390 *
16391 * R.reduceIndexed(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 }
16392 */
16393 var reduceIndexed = _curry3(function reduceIndexed(fn, acc, list) {
16394 var idx = -1, len = list.length;
16395 while (++idx < len) {
16396 acc = fn(acc, list[idx], idx, list);
16397 }
16398 return acc;
16399 });
16400
16401 /**
16402 * Returns a single item by iterating through the list, successively calling the iterator
16403 * function and passing it an accumulator value and the current value from the array, and
16404 * then passing the result to the next call.
16405 *
16406 * Similar to `reduce`, except moves through the input list from the right to the left.
16407 *
16408 * The iterator function receives two values: *(acc, value)*
16409 *
16410 * Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse arrays), unlike
16411 * the native `Array.prototype.reduce` method. For more details on this behavior, see:
16412 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
16413 *
16414 * @func
16415 * @memberOf R
16416 * @category List
16417 * @sig (a,b -> a) -> a -> [b] -> a
16418 * @param {Function} fn The iterator function. Receives two values, the accumulator and the
16419 * current element from the array.
16420 * @param {*} acc The accumulator value.
16421 * @param {Array} list The list to iterate over.
16422 * @return {*} The final, accumulated value.
16423 * @example
16424 *
16425 * var pairs = [ ['a', 1], ['b', 2], ['c', 3] ];
16426 * var flattenPairs = function(acc, pair) {
16427 * return acc.concat(pair);
16428 * };
16429 *
16430 * R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ]
16431 */
16432 var reduceRight = _curry3(function reduceRight(fn, acc, list) {
16433 var idx = list.length;
16434 while (--idx >= 0) {
16435 acc = fn(acc, list[idx]);
16436 }
16437 return acc;
16438 });
16439
16440 /**
16441 * Like `reduceRight`, but passes additional parameters to the predicate function. Moves through
16442 * the input list from the right to the left.
16443 *
16444 * The iterator function receives four values: *(acc, value, index, list)*.
16445 *
16446 * Note: `R.reduceRightIndexed` does not skip deleted or unassigned indices (sparse arrays),
16447 * unlike the native `Array.prototype.reduce` method. For more details on this behavior,
16448 * see:
16449 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
16450 *
16451 * @func
16452 * @memberOf R
16453 * @category List
16454 * @sig (a,b,i,[b] -> a -> [b] -> a
16455 * @param {Function} fn The iterator function. Receives four values: the accumulator, the
16456 * current element from `list`, that element's index, and the entire `list` itself.
16457 * @param {*} acc The accumulator value.
16458 * @param {Array} list The list to iterate over.
16459 * @return {*} The final, accumulated value.
16460 * @example
16461 *
16462 * var letters = ['a', 'b', 'c'];
16463 * var objectify = function(accObject, elem, idx, list) {
16464 * accObject[elem] = idx;
16465 * return accObject;
16466 * };
16467 *
16468 * R.reduceRightIndexed(objectify, {}, letters); //=> { 'c': 2, 'b': 1, 'a': 0 }
16469 */
16470 var reduceRightIndexed = _curry3(function reduceRightIndexed(fn, acc, list) {
16471 var idx = list.length;
16472 while (--idx >= 0) {
16473 acc = fn(acc, list[idx], idx, list);
16474 }
16475 return acc;
16476 });
16477
16478 /**
16479 * Like `reject`, but passes additional parameters to the predicate function. The predicate
16480 * function is passed three arguments: *(value, index, list)*.
16481 *
16482 * @func
16483 * @memberOf R
16484 * @category List
16485 * @sig (a, i, [a] -> Boolean) -> [a] -> [a]
16486 * @param {Function} fn The function called per iteration.
16487 * @param {Array} list The collection to iterate over.
16488 * @return {Array} The new filtered array.
16489 * @example
16490 *
16491 * var lastTwo = function(val, idx, list) {
16492 * return list.length - idx <= 2;
16493 * };
16494 *
16495 * R.rejectIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3]
16496 */
16497 var rejectIndexed = _curry2(function rejectIndexed(fn, list) {
16498 return _filterIndexed(_complement(fn), list);
16499 });
16500
16501 /**
16502 * Removes the sub-list of `list` starting at index `start` and containing
16503 * `count` elements. _Note that this is not destructive_: it returns a
16504 * copy of the list with the changes.
16505 * <small>No lists have been harmed in the application of this function.</small>
16506 *
16507 * @func
16508 * @memberOf R
16509 * @category List
16510 * @sig Number -> Number -> [a] -> [a]
16511 * @param {Number} start The position to start removing elements
16512 * @param {Number} count The number of elements to remove
16513 * @param {Array} list The list to remove from
16514 * @return {Array} A new Array with `count` elements from `start` removed.
16515 * @example
16516 *
16517 * R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]
16518 */
16519 var remove = _curry3(function remove(start, count, list) {
16520 return _concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count)));
16521 });
16522
16523 /**
16524 * Replace a substring or regex match in a string with a replacement.
16525 *
16526 * @func
16527 * @memberOf R
16528 * @category String
16529 * @sig RegExp|String -> String -> String -> String
16530 * @param {RegExp|String} pattern A regular expression or a substring to match.
16531 * @param {String} replacement The string to replace the matches with.
16532 * @param {String} str The String to do the search and replacement in.
16533 * @return {String} The result.
16534 * @example
16535 *
16536 * R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo'
16537 * R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo'
16538 *
16539 * // Use the "g" (global) flag to replace all occurrences:
16540 * R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar'
16541 */
16542 var replace = _curry3(function replace(regex, replacement, str) {
16543 return str.replace(regex, replacement);
16544 });
16545
16546 /**
16547 * Returns a new list with the same elements as the original list, just
16548 * in the reverse order.
16549 *
16550 * @func
16551 * @memberOf R
16552 * @category List
16553 * @sig [a] -> [a]
16554 * @param {Array} list The list to reverse.
16555 * @return {Array} A copy of the list in reverse order.
16556 * @example
16557 *
16558 * R.reverse([1, 2, 3]); //=> [3, 2, 1]
16559 * R.reverse([1, 2]); //=> [2, 1]
16560 * R.reverse([1]); //=> [1]
16561 * R.reverse([]); //=> []
16562 */
16563 var reverse = _curry1(function reverse(list) {
16564 return _slice(list).reverse();
16565 });
16566
16567 /**
16568 * Scan is similar to reduce, but returns a list of successively reduced values from the left
16569 *
16570 * @func
16571 * @memberOf R
16572 * @category List
16573 * @sig (a,b -> a) -> a -> [b] -> [a]
16574 * @param {Function} fn The iterator function. Receives two values, the accumulator and the
16575 * current element from the array
16576 * @param {*} acc The accumulator value.
16577 * @param {Array} list The list to iterate over.
16578 * @return {Array} A list of all intermediately reduced values.
16579 * @example
16580 *
16581 * var numbers = [1, 2, 3, 4];
16582 * var factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24]
16583 */
16584 var scan = _curry3(function scan(fn, acc, list) {
16585 var idx = 0, len = list.length + 1, result = [acc];
16586 while (++idx < len) {
16587 acc = fn(acc, list[idx - 1]);
16588 result[idx] = acc;
16589 }
16590 return result;
16591 });
16592
16593 /**
16594 * Returns a copy of the list, sorted according to the comparator function, which should accept two values at a
16595 * time and return a negative number if the first value is smaller, a positive number if it's larger, and zero
16596 * if they are equal. Please note that this is a **copy** of the list. It does not modify the original.
16597 *
16598 * @func
16599 * @memberOf R
16600 * @category List
16601 * @sig (a,a -> Number) -> [a] -> [a]
16602 * @param {Function} comparator A sorting function :: a -> b -> Int
16603 * @param {Array} list The list to sort
16604 * @return {Array} a new array with its elements sorted by the comparator function.
16605 * @example
16606 *
16607 * var diff = function(a, b) { return a - b; };
16608 * R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]
16609 */
16610 var sort = _curry2(function sort(comparator, list) {
16611 return _slice(list).sort(comparator);
16612 });
16613
16614 /**
16615 * Sorts the list according to a key generated by the supplied function.
16616 *
16617 * @func
16618 * @memberOf R
16619 * @category Relation
16620 * @sig (a -> String) -> [a] -> [a]
16621 * @param {Function} fn The function mapping `list` items to keys.
16622 * @param {Array} list The list to sort.
16623 * @return {Array} A new list sorted by the keys generated by `fn`.
16624 * @example
16625 *
16626 * var sortByFirstItem = R.sortBy(prop(0));
16627 * var sortByNameCaseInsensitive = R.sortBy(compose(R.toLower, prop('name')));
16628 * var pairs = [[-1, 1], [-2, 2], [-3, 3]];
16629 * sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]]
16630 * var alice = {
16631 * name: 'ALICE',
16632 * age: 101
16633 * };
16634 * var bob = {
16635 * name: 'Bob',
16636 * age: -10
16637 * };
16638 * var clara = {
16639 * name: 'clara',
16640 * age: 314.159
16641 * };
16642 * var people = [clara, bob, alice];
16643 * sortByNameCaseInsensitive(people); //=> [alice, bob, clara]
16644 */
16645 var sortBy = _curry2(function sortBy(fn, list) {
16646 return _slice(list).sort(function (a, b) {
16647 var aa = fn(a);
16648 var bb = fn(b);
16649 return aa < bb ? -1 : aa > bb ? 1 : 0;
16650 });
16651 });
16652
16653 /**
16654 * Finds the first index of a substring in a string, returning -1 if it's not present
16655 *
16656 * @func
16657 * @memberOf R
16658 * @category String
16659 * @sig String -> String -> Number
16660 * @param {String} c A string to find.
16661 * @param {String} str The string to search in
16662 * @return {Number} The first index of `c` or -1 if not found.
16663 * @example
16664 *
16665 * R.strIndexOf('c', 'abcdefg'); //=> 2
16666 */
16667 var strIndexOf = _curry2(function strIndexOf(c, str) {
16668 return str.indexOf(c);
16669 });
16670
16671 /**
16672 *
16673 * Finds the last index of a substring in a string, returning -1 if it's not present
16674 *
16675 * @func
16676 * @memberOf R
16677 * @category String
16678 * @sig String -> String -> Number
16679 * @param {String} c A string to find.
16680 * @param {String} str The string to search in
16681 * @return {Number} The last index of `c` or -1 if not found.
16682 * @example
16683 *
16684 * R.strLastIndexOf('a', 'banana split'); //=> 5
16685 */
16686 var strLastIndexOf = _curry2(function (c, str) {
16687 return str.lastIndexOf(c);
16688 });
16689
16690 /**
16691 * Subtracts two numbers. Equivalent to `a - b` but curried.
16692 *
16693 * @func
16694 * @memberOf R
16695 * @category Math
16696 * @sig Number -> Number -> Number
16697 * @param {Number} a The first value.
16698 * @param {Number} b The second value.
16699 * @return {Number} The result of `a - b`.
16700 * @example
16701 *
16702 * R.subtract(10, 8); //=> 2
16703 *
16704 * var minus5 = R.subtract(R.__, 5);
16705 * minus5(17); //=> 12
16706 *
16707 * var complementaryAngle = R.subtract(90);
16708 * complementaryAngle(30); //=> 60
16709 * complementaryAngle(72); //=> 18
16710 */
16711 var subtract = _curry2(function subtract(a, b) {
16712 return a - b;
16713 });
16714
16715 /**
16716 * Runs the given function with the supplied object, then returns the object.
16717 *
16718 * @func
16719 * @memberOf R
16720 * @category Function
16721 * @sig (a -> *) -> a -> a
16722 * @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away.
16723 * @param {*} x
16724 * @return {*} `x`.
16725 * @example
16726 *
16727 * var sayX = function(x) { console.log('x is ' + x); };
16728 * R.tap(sayX, 100); //=> 100
16729 * //-> 'x is 100'
16730 */
16731 var tap = _curry2(function tap(fn, x) {
16732 fn(x);
16733 return x;
16734 });
16735
16736 /**
16737 * Determines whether a given string matches a given regular expression.
16738 *
16739 * @func
16740 * @memberOf R
16741 * @category String
16742 * @sig RegExp -> String -> Boolean
16743 * @param {RegExp} pattern
16744 * @param {String} str
16745 * @return {Boolean}
16746 * @example
16747 *
16748 * R.test(/^x/, 'xyz'); //=> true
16749 * R.test(/^y/, 'xyz'); //=> false
16750 */
16751 var test = _curry2(function test(pattern, str) {
16752 return _cloneRegExp(pattern).test(str);
16753 });
16754
16755 /**
16756 * Calls an input function `n` times, returning an array containing the results of those
16757 * function calls.
16758 *
16759 * `fn` is passed one argument: The current value of `n`, which begins at `0` and is
16760 * gradually incremented to `n - 1`.
16761 *
16762 * @func
16763 * @memberOf R
16764 * @category List
16765 * @sig (i -> a) -> i -> [a]
16766 * @param {Function} fn The function to invoke. Passed one argument, the current value of `n`.
16767 * @param {Number} n A value between `0` and `n - 1`. Increments after each function call.
16768 * @return {Array} An array containing the return values of all calls to `fn`.
16769 * @example
16770 *
16771 * R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]
16772 */
16773 var times = _curry2(function times(fn, n) {
16774 var len = Number(n);
16775 var list = new Array(len);
16776 var idx = 0;
16777 while (idx < len) {
16778 list[idx] = fn(idx);
16779 idx += 1;
16780 }
16781 return list;
16782 });
16783
16784 /**
16785 * Converts an object into an array of key, value arrays.
16786 * Only the object's own properties are used.
16787 * Note that the order of the output array is not guaranteed to be
16788 * consistent across different JS platforms.
16789 *
16790 * @func
16791 * @memberOf R
16792 * @category Object
16793 * @sig {String: *} -> [[String,*]]
16794 * @param {Object} obj The object to extract from
16795 * @return {Array} An array of key, value arrays from the object's own properties.
16796 * @example
16797 *
16798 * R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]]
16799 */
16800 var toPairs = _curry1(function toPairs(obj) {
16801 var pairs = [];
16802 for (var prop in obj) {
16803 if (_has(prop, obj)) {
16804 pairs[pairs.length] = [
16805 prop,
16806 obj[prop]
16807 ];
16808 }
16809 }
16810 return pairs;
16811 });
16812
16813 /**
16814 * Converts an object into an array of key, value arrays.
16815 * The object's own properties and prototype properties are used.
16816 * Note that the order of the output array is not guaranteed to be
16817 * consistent across different JS platforms.
16818 *
16819 * @func
16820 * @memberOf R
16821 * @category Object
16822 * @sig {String: *} -> [[String,*]]
16823 * @param {Object} obj The object to extract from
16824 * @return {Array} An array of key, value arrays from the object's own
16825 * and prototype properties.
16826 * @example
16827 *
16828 * var F = function() { this.x = 'X'; };
16829 * F.prototype.y = 'Y';
16830 * var f = new F();
16831 * R.toPairsIn(f); //=> [['x','X'], ['y','Y']]
16832 */
16833 var toPairsIn = _curry1(function toPairsIn(obj) {
16834 var pairs = [];
16835 for (var prop in obj) {
16836 pairs[pairs.length] = [
16837 prop,
16838 obj[prop]
16839 ];
16840 }
16841 return pairs;
16842 });
16843
16844 /**
16845 * Removes (strips) whitespace from both ends of the string.
16846 *
16847 * @func
16848 * @memberOf R
16849 * @category String
16850 * @sig String -> String
16851 * @param {String} str The string to trim.
16852 * @return {String} Trimmed version of `str`.
16853 * @example
16854 *
16855 * R.trim(' xyz '); //=> 'xyz'
16856 * R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z']
16857 */
16858 var trim = function () {
16859 var ws = '\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' + '\u2029\uFEFF';
16860 var zeroWidth = '\u200B';
16861 var hasProtoTrim = typeof String.prototype.trim === 'function';
16862 if (!hasProtoTrim || (ws.trim() || !zeroWidth.trim())) {
16863 return _curry1(function trim(str) {
16864 var beginRx = new RegExp('^[' + ws + '][' + ws + ']*');
16865 var endRx = new RegExp('[' + ws + '][' + ws + ']*$');
16866 return str.replace(beginRx, '').replace(endRx, '');
16867 });
16868 } else {
16869 return _curry1(function trim(str) {
16870 return str.trim();
16871 });
16872 }
16873 }();
16874
16875 /**
16876 * Gives a single-word string description of the (native) type of a value, returning such
16877 * answers as 'Object', 'Number', 'Array', or 'Null'. Does not attempt to distinguish user
16878 * Object types any further, reporting them all as 'Object'.
16879 *
16880 * @func
16881 * @memberOf R
16882 * @category Type
16883 * @sig (* -> {*}) -> String
16884 * @param {*} val The value to test
16885 * @return {String}
16886 * @example
16887 *
16888 * R.type({}); //=> "Object"
16889 * R.type(1); //=> "Number"
16890 * R.type(false); //=> "Boolean"
16891 * R.type('s'); //=> "String"
16892 * R.type(null); //=> "Null"
16893 * R.type([]); //=> "Array"
16894 * R.type(/[A-z]/); //=> "RegExp"
16895 */
16896 var type = _curry1(function type(val) {
16897 return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1);
16898 });
16899
16900 /**
16901 * Takes a function `fn`, which takes a single array argument, and returns
16902 * a function which:
16903 *
16904 * - takes any number of positional arguments;
16905 * - passes these arguments to `fn` as an array; and
16906 * - returns the result.
16907 *
16908 * In other words, R.unapply derives a variadic function from a function
16909 * which takes an array. R.unapply is the inverse of R.apply.
16910 *
16911 * @func
16912 * @memberOf R
16913 * @category Function
16914 * @sig ([*...] -> a) -> (*... -> a)
16915 * @param {Function} fn
16916 * @return {Function}
16917 * @see R.apply
16918 * @example
16919 *
16920 * R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]'
16921 */
16922 var unapply = _curry1(function unapply(fn) {
16923 return function () {
16924 return fn(_slice(arguments));
16925 };
16926 });
16927
16928 /**
16929 * Wraps a function of any arity (including nullary) in a function that accepts exactly 1
16930 * parameter. Any extraneous parameters will not be passed to the supplied function.
16931 *
16932 * @func
16933 * @memberOf R
16934 * @category Function
16935 * @sig (* -> b) -> (a -> b)
16936 * @param {Function} fn The function to wrap.
16937 * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
16938 * arity 1.
16939 * @example
16940 *
16941 * var takesTwoArgs = function(a, b) {
16942 * return [a, b];
16943 * };
16944 * takesTwoArgs.length; //=> 2
16945 * takesTwoArgs(1, 2); //=> [1, 2]
16946 *
16947 * var takesOneArg = R.unary(takesTwoArgs);
16948 * takesOneArg.length; //=> 1
16949 * // Only 1 argument is passed to the wrapped function
16950 * takesOneArg(1, 2); //=> [1, undefined]
16951 */
16952 var unary = _curry1(function unary(fn) {
16953 return nAry(1, fn);
16954 });
16955
16956 /**
16957 * Returns a function of arity `n` from a (manually) curried function.
16958 *
16959 * @func
16960 * @memberOf R
16961 * @category Function
16962 * @sig Number -> (a -> b) -> (a -> c)
16963 * @param {Number} length The arity for the returned function.
16964 * @param {Function} fn The function to uncurry.
16965 * @return {Function} A new function.
16966 * @see R.curry
16967 * @example
16968 *
16969 * var addFour = function(a) {
16970 * return function(b) {
16971 * return function(c) {
16972 * return function(d) {
16973 * return a + b + c + d;
16974 * };
16975 * };
16976 * };
16977 * };
16978 *
16979 * var uncurriedAddFour = R.uncurryN(4, addFour);
16980 * curriedAddFour(1, 2, 3, 4); //=> 10
16981 */
16982 var uncurryN = _curry2(function uncurryN(depth, fn) {
16983 return curryN(depth, function () {
16984 var currentDepth = 1;
16985 var value = fn;
16986 var idx = 0;
16987 var endIdx;
16988 while (currentDepth <= depth && typeof value === 'function') {
16989 endIdx = currentDepth === depth ? arguments.length : idx + value.length;
16990 value = value.apply(this, _slice(arguments, idx, endIdx));
16991 currentDepth += 1;
16992 idx = endIdx;
16993 }
16994 return value;
16995 });
16996 });
16997
16998 /**
16999 * Builds a list from a seed value. Accepts an iterator function, which returns either false
17000 * to stop iteration or an array of length 2 containing the value to add to the resulting
17001 * list and the seed to be used in the next call to the iterator function.
17002 *
17003 * The iterator function receives one argument: *(seed)*.
17004 *
17005 * @func
17006 * @memberOf R
17007 * @category List
17008 * @sig (a -> [b]) -> * -> [b]
17009 * @param {Function} fn The iterator function. receives one argument, `seed`, and returns
17010 * either false to quit iteration or an array of length two to proceed. The element
17011 * at index 0 of this array will be added to the resulting array, and the element
17012 * at index 1 will be passed to the next call to `fn`.
17013 * @param {*} seed The seed value.
17014 * @return {Array} The final list.
17015 * @example
17016 *
17017 * var f = function(n) { return n > 50 ? false : [-n, n + 10] };
17018 * R.unfold(f, 10); //=> [-10, -20, -30, -40, -50]
17019 */
17020 var unfold = _curry2(function unfold(fn, seed) {
17021 var pair = fn(seed);
17022 var result = [];
17023 while (pair && pair.length) {
17024 result[result.length] = pair[0];
17025 pair = fn(pair[1]);
17026 }
17027 return result;
17028 });
17029
17030 /**
17031 * Returns a new list containing only one copy of each element in the original list, based
17032 * upon the value returned by applying the supplied predicate to two list elements. Prefers
17033 * the first item if two items compare equal based on the predicate.
17034 *
17035 * @func
17036 * @memberOf R
17037 * @category List
17038 * @sig (a, a -> Boolean) -> [a] -> [a]
17039 * @param {Function} pred A predicate used to test whether two items are equal.
17040 * @param {Array} list The array to consider.
17041 * @return {Array} The list of unique items.
17042 * @example
17043 *
17044 * var strEq = function(a, b) { return String(a) === String(b); };
17045 * R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2]
17046 * R.uniqWith(strEq)([{}, {}]); //=> [{}]
17047 * R.uniqWith(strEq)([1, '1', 1]); //=> [1]
17048 * R.uniqWith(strEq)(['1', 1, 1]); //=> ['1']
17049 */
17050 var uniqWith = _curry2(function uniqWith(pred, list) {
17051 var idx = -1, len = list.length;
17052 var result = [], item;
17053 while (++idx < len) {
17054 item = list[idx];
17055 if (!_containsWith(pred, item, result)) {
17056 result[result.length] = item;
17057 }
17058 }
17059 return result;
17060 });
17061
17062 /**
17063 * Returns a new copy of the array with the element at the
17064 * provided index replaced with the given value.
17065 *
17066 * @func
17067 * @memberOf R
17068 * @category List
17069 * @sig Number -> a -> [a] -> [a]
17070 * @param {Number} idx The index to update.
17071 * @param {*} x The value to exist at the given index of the returned array.
17072 * @param {Array|Arguments} list The source array-like object to be updated.
17073 * @return {Array} A copy of `list` with the value at index `idx` replaced with `x`.
17074 * @example
17075 *
17076 * R.update(1, 11, [0, 1, 2]); //=> [0, 11, 2]
17077 * R.update(1)(11)([0, 1, 2]); //=> [0, 11, 2]
17078 */
17079 var update = _curry3(function (idx, x, list) {
17080 return adjust(always(x), idx, list);
17081 });
17082
17083 /**
17084 * Returns a list of all the properties, including prototype properties,
17085 * of the supplied object.
17086 * Note that the order of the output array is not guaranteed to be
17087 * consistent across different JS platforms.
17088 *
17089 * @func
17090 * @memberOf R
17091 * @category Object
17092 * @sig {k: v} -> [v]
17093 * @param {Object} obj The object to extract values from
17094 * @return {Array} An array of the values of the object's own and prototype properties.
17095 * @example
17096 *
17097 * var F = function() { this.x = 'X'; };
17098 * F.prototype.y = 'Y';
17099 * var f = new F();
17100 * R.valuesIn(f); //=> ['X', 'Y']
17101 */
17102 var valuesIn = _curry1(function valuesIn(obj) {
17103 var prop, vs = [];
17104 for (prop in obj) {
17105 vs[vs.length] = obj[prop];
17106 }
17107 return vs;
17108 });
17109
17110 /**
17111 * Takes a spec object and a test object; returns true if the test satisfies
17112 * the spec. Each of the spec's own properties must be a predicate function.
17113 * Each predicate is applied to the value of the corresponding property of
17114 * the test object. `where` returns true if all the predicates return true,
17115 * false otherwise.
17116 *
17117 * `where` is well suited to declaratively expressing constraints for other
17118 * functions such as `filter` and `find`.
17119 *
17120 * @func
17121 * @memberOf R
17122 * @category Object
17123 * @sig {String: (* -> Boolean)} -> {String: *} -> Boolean
17124 * @param {Object} spec
17125 * @param {Object} testObj
17126 * @return {Boolean}
17127 * @example
17128 *
17129 * // pred :: Object -> Boolean
17130 * var pred = R.where({
17131 * a: R.eq('foo'),
17132 * b: R.complement(R.eq('bar')),
17133 * x: R.gt(_, 10),
17134 * y: R.lt(_, 20)
17135 * });
17136 *
17137 * pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true
17138 * pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false
17139 * pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false
17140 * pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false
17141 * pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false
17142 */
17143 var where = _curry2(function where(spec, testObj) {
17144 for (var prop in spec) {
17145 if (_has(prop, spec) && !spec[prop](testObj[prop])) {
17146 return false;
17147 }
17148 }
17149 return true;
17150 });
17151
17152 /**
17153 * Wrap a function inside another to allow you to make adjustments to the parameters, or do
17154 * other processing either before the internal function is called or with its results.
17155 *
17156 * @func
17157 * @memberOf R
17158 * @category Function
17159 * @sig (a... -> b) -> ((a... -> b) -> a... -> c) -> (a... -> c)
17160 * @param {Function} fn The function to wrap.
17161 * @param {Function} wrapper The wrapper function.
17162 * @return {Function} The wrapped function.
17163 * @example
17164 *
17165 * var greet = function(name) {return 'Hello ' + name;};
17166 *
17167 * var shoutedGreet = R.wrap(greet, function(gr, name) {
17168 * return gr(name).toUpperCase();
17169 * });
17170 * shoutedGreet("Kathy"); //=> "HELLO KATHY"
17171 *
17172 * var shortenedGreet = R.wrap(greet, function(gr, name) {
17173 * return gr(name.substring(0, 3));
17174 * });
17175 * shortenedGreet("Robert"); //=> "Hello Rob"
17176 */
17177 var wrap = _curry2(function wrap(fn, wrapper) {
17178 return curryN(fn.length, function () {
17179 return wrapper.apply(this, _concat([fn], arguments));
17180 });
17181 });
17182
17183 /**
17184 * Creates a new list out of the two supplied by creating each possible
17185 * pair from the lists.
17186 *
17187 * @func
17188 * @memberOf R
17189 * @category List
17190 * @sig [a] -> [b] -> [[a,b]]
17191 * @param {Array} as The first list.
17192 * @param {Array} bs The second list.
17193 * @return {Array} The list made by combining each possible pair from
17194 * `as` and `bs` into pairs (`[a, b]`).
17195 * @example
17196 *
17197 * R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
17198 */
17199 // = xprodWith(prepend); (takes about 3 times as long...)
17200 var xprod = _curry2(function xprod(a, b) {
17201 // = xprodWith(prepend); (takes about 3 times as long...)
17202 var idx = -1;
17203 var ilen = a.length;
17204 var j;
17205 var jlen = b.length;
17206 var result = [];
17207 while (++idx < ilen) {
17208 j = -1;
17209 while (++j < jlen) {
17210 result[result.length] = [
17211 a[idx],
17212 b[j]
17213 ];
17214 }
17215 }
17216 return result;
17217 });
17218
17219 /**
17220 * Creates a new list out of the two supplied by pairing up
17221 * equally-positioned items from both lists. The returned list is
17222 * truncated to the length of the shorter of the two input lists.
17223 * Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`.
17224 *
17225 * @func
17226 * @memberOf R
17227 * @category List
17228 * @sig [a] -> [b] -> [[a,b]]
17229 * @param {Array} list1 The first array to consider.
17230 * @param {Array} list2 The second array to consider.
17231 * @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`.
17232 * @example
17233 *
17234 * R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]
17235 */
17236 var zip = _curry2(function zip(a, b) {
17237 var rv = [];
17238 var idx = -1;
17239 var len = Math.min(a.length, b.length);
17240 while (++idx < len) {
17241 rv[idx] = [
17242 a[idx],
17243 b[idx]
17244 ];
17245 }
17246 return rv;
17247 });
17248
17249 /**
17250 * Creates a new object out of a list of keys and a list of values.
17251 *
17252 * @func
17253 * @memberOf R
17254 * @category List
17255 * @sig [String] -> [*] -> {String: *}
17256 * @param {Array} keys The array that will be properties on the output object.
17257 * @param {Array} values The list of values on the output object.
17258 * @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`.
17259 * @example
17260 *
17261 * R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3}
17262 */
17263 var zipObj = _curry2(function zipObj(keys, values) {
17264 var idx = -1, len = keys.length, out = {};
17265 while (++idx < len) {
17266 out[keys[idx]] = values[idx];
17267 }
17268 return out;
17269 });
17270
17271 /**
17272 * Creates a new list out of the two supplied by applying the function to
17273 * each equally-positioned pair in the lists. The returned list is
17274 * truncated to the length of the shorter of the two input lists.
17275 *
17276 * @function
17277 * @memberOf R
17278 * @category List
17279 * @sig (a,b -> c) -> [a] -> [b] -> [c]
17280 * @param {Function} fn The function used to combine the two elements into one value.
17281 * @param {Array} list1 The first array to consider.
17282 * @param {Array} list2 The second array to consider.
17283 * @return {Array} The list made by combining same-indexed elements of `list1` and `list2`
17284 * using `fn`.
17285 * @example
17286 *
17287 * var f = function(x, y) {
17288 * // ...
17289 * };
17290 * R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']);
17291 * //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]
17292 */
17293 var zipWith = _curry3(function zipWith(fn, a, b) {
17294 var rv = [], idx = -1, len = Math.min(a.length, b.length);
17295 while (++idx < len) {
17296 rv[idx] = fn(a[idx], b[idx]);
17297 }
17298 return rv;
17299 });
17300
17301 /**
17302 * A function that always returns `false`. Any passed in parameters are ignored.
17303 *
17304 * @func
17305 * @memberOf R
17306 * @category Function
17307 * @sig * -> false
17308 * @see R.always
17309 * @return {Boolean} false
17310 * @example
17311 *
17312 * R.F(); //=> false
17313 */
17314 var F = always(false);
17315
17316 /**
17317 * A function that always returns `true`. Any passed in parameters are ignored.
17318 *
17319 * @func
17320 * @memberOf R
17321 * @category Function
17322 * @sig * -> true
17323 * @see R.always
17324 * @return {Boolean} `true`.
17325 * @example
17326 *
17327 * R.T(); //=> true
17328 */
17329 var T = always(true);
17330
17331 var _append = function _append(el, list) {
17332 return _concat(list, [el]);
17333 };
17334
17335 var _assocPath = function _assocPath(path, val, obj) {
17336 switch (path.length) {
17337 case 0:
17338 return obj;
17339 case 1:
17340 return _assoc(path[0], val, obj);
17341 default:
17342 return _assoc(path[0], _assocPath(_slice(path, 1), val, Object(obj[path[0]])), obj);
17343 }
17344 };
17345
17346 /**
17347 * Copies an object.
17348 *
17349 * @private
17350 * @param {*} value The value to be copied
17351 * @param {Array} refFrom Array containing the source references
17352 * @param {Array} refTo Array containing the copied source references
17353 * @return {*} The copied value.
17354 */
17355 var _baseCopy = function _baseCopy(value, refFrom, refTo) {
17356 var copy = function copy(copiedValue) {
17357 var len = refFrom.length;
17358 var idx = -1;
17359 while (++idx < len) {
17360 if (value === refFrom[idx]) {
17361 return refTo[idx];
17362 }
17363 }
17364 refFrom[idx + 1] = value;
17365 refTo[idx + 1] = copiedValue;
17366 for (var key in value) {
17367 copiedValue[key] = _baseCopy(value[key], refFrom, refTo);
17368 }
17369 return copiedValue;
17370 };
17371 switch (type(value)) {
17372 case 'Object':
17373 return copy({});
17374 case 'Array':
17375 return copy([]);
17376 case 'Date':
17377 return new Date(value);
17378 case 'RegExp':
17379 return _cloneRegExp(value);
17380 default:
17381 return value;
17382 }
17383 };
17384
17385 /**
17386 * Similar to hasMethod, this checks whether a function has a [methodname]
17387 * function. If it isn't an array it will execute that function otherwise it will
17388 * default to the ramda implementation.
17389 *
17390 * @private
17391 * @param {Function} fn ramda implemtation
17392 * @param {String} methodname property to check for a custom implementation
17393 * @return {Object} Whatever the return value of the method is.
17394 */
17395 var _checkForMethod = function _checkForMethod(methodname, fn) {
17396 return function () {
17397 var length = arguments.length;
17398 if (length === 0) {
17399 return fn();
17400 }
17401 var obj = arguments[length - 1];
17402 return _isArray(obj) || typeof obj[methodname] !== 'function' ? fn.apply(this, arguments) : obj[methodname].apply(obj, _slice(arguments, 0, length - 1));
17403 };
17404 };
17405
17406 var _composeL = function _composeL(innerLens, outerLens) {
17407 return lens(_compose(innerLens, outerLens), function (x, source) {
17408 var newInnerValue = innerLens.set(x, outerLens(source));
17409 return outerLens.set(newInnerValue, source);
17410 });
17411 };
17412
17413 /**
17414 * A right-associative two-argument composition function like `_compose`
17415 * but with automatic handling of promises (or, more precisely,
17416 * "thenables"). This function is used to construct a more general
17417 * `composeP` function, which accepts any number of arguments.
17418 *
17419 * @private
17420 * @category Function
17421 * @param {Function} f A function.
17422 * @param {Function} g A function.
17423 * @return {Function} A new function that is the equivalent of `f(g(x))`.
17424 * @example
17425 *
17426 * var Q = require('q');
17427 * var double = function(x) { return x * 2; };
17428 * var squareAsync = function(x) { return Q.when(x * x); };
17429 * var squareAsyncThenDouble = _composeP(double, squareAsync);
17430 *
17431 * squareAsyncThenDouble(5)
17432 * .then(function(result) {
17433 * // the result is now 50.
17434 * });
17435 */
17436 var _composeP = function _composeP(f, g) {
17437 return function () {
17438 var context = this;
17439 var value = g.apply(this, arguments);
17440 if (_isThenable(value)) {
17441 return value.then(function (result) {
17442 return f.call(context, result);
17443 });
17444 } else {
17445 return f.call(this, value);
17446 }
17447 };
17448 };
17449
17450 var _contains = function _contains(a, list) {
17451 return _indexOf(list, a) >= 0;
17452 };
17453
17454 /*
17455 * Returns a function that makes a multi-argument version of compose from
17456 * either _compose or _composeP.
17457 */
17458 var _createComposer = function _createComposer(composeFunction) {
17459 return function () {
17460 var idx = arguments.length - 1;
17461 var fn = arguments[idx];
17462 var length = fn.length;
17463 while (--idx >= 0) {
17464 fn = composeFunction(arguments[idx], fn);
17465 }
17466 return arity(length, fn);
17467 };
17468 };
17469
17470 /**
17471 * Create a function which takes a list
17472 * and determines the winning value by a comparator. Used internally
17473 * by `R.max` and `R.min`
17474 *
17475 * @private
17476 * @param {Function} compatator a function to compare two items
17477 * @param {*} intialVal, default value if nothing else wins
17478 * @category Math
17479 * @return {Function}
17480 */
17481 var _createMaxMin = function _createMaxMin(comparator, initialVal) {
17482 return _curry1(function (list) {
17483 var idx = -1, winner = initialVal, computed;
17484 while (++idx < list.length) {
17485 computed = +list[idx];
17486 if (comparator(computed, winner)) {
17487 winner = computed;
17488 }
17489 }
17490 return winner;
17491 });
17492 };
17493
17494 var _createPartialApplicator = function _createPartialApplicator(concat) {
17495 return function (fn) {
17496 var args = _slice(arguments, 1);
17497 return arity(Math.max(0, fn.length - args.length), function () {
17498 return fn.apply(this, concat(args, arguments));
17499 });
17500 };
17501 };
17502
17503 /**
17504 * Returns a function that dispatches with different strategies based on the
17505 * object in list position (last argument). If it is an array, executes [fn].
17506 * Otherwise, if it has a function with [methodname], it will execute that
17507 * function (functor case). Otherwise, if it is a transformer, uses transducer
17508 * [xf] to return a new transformer (transducer case). Otherwise, it will
17509 * default to executing [fn].
17510 *
17511 * @private
17512 * @param {String} methodname property to check for a custom implementation
17513 * @param {Function} xf transducer to initialize if object is transformer
17514 * @param {Function} fn default ramda implementation
17515 * @return {Function} A function that dispatches on object in list position
17516 */
17517 var _dispatchable = function _dispatchable(methodname, xf, fn) {
17518 return function () {
17519 var length = arguments.length;
17520 if (length === 0) {
17521 return fn();
17522 }
17523 var obj = arguments[length - 1];
17524 if (!_isArray(obj)) {
17525 var args = _slice(arguments, 0, length - 1);
17526 if (typeof obj[methodname] === 'function') {
17527 return obj[methodname].apply(obj, args);
17528 }
17529 if (_isTransformer(obj)) {
17530 var transducer = xf.apply(null, args);
17531 return transducer(obj);
17532 }
17533 }
17534 return fn.apply(this, arguments);
17535 };
17536 };
17537
17538 var _dissocPath = function _dissocPath(path, obj) {
17539 switch (path.length) {
17540 case 0:
17541 return obj;
17542 case 1:
17543 return _dissoc(path[0], obj);
17544 default:
17545 var head = path[0];
17546 var tail = _slice(path, 1);
17547 return obj[head] == null ? obj : _assoc(head, _dissocPath(tail, obj[head]), obj);
17548 }
17549 };
17550
17551 /**
17552 * Private function that determines whether or not a provided object has a given method.
17553 * Does not ignore methods stored on the object's prototype chain. Used for dynamically
17554 * dispatching Ramda methods to non-Array objects.
17555 *
17556 * @private
17557 * @param {String} methodName The name of the method to check for.
17558 * @param {Object} obj The object to test.
17559 * @return {Boolean} `true` has a given method, `false` otherwise.
17560 * @example
17561 *
17562 * var person = { name: 'John' };
17563 * person.shout = function() { alert(this.name); };
17564 *
17565 * _hasMethod('shout', person); //=> true
17566 * _hasMethod('foo', person); //=> false
17567 */
17568 var _hasMethod = function _hasMethod(methodName, obj) {
17569 return obj != null && !_isArray(obj) && typeof obj[methodName] === 'function';
17570 };
17571
17572 /**
17573 * `_makeFlat` is a helper function that returns a one-level or fully recursive function
17574 * based on the flag passed in.
17575 *
17576 * @private
17577 */
17578 var _makeFlat = function _makeFlat(recursive) {
17579 return function flatt(list) {
17580 var value, result = [], idx = -1, j, ilen = list.length, jlen;
17581 while (++idx < ilen) {
17582 if (isArrayLike(list[idx])) {
17583 value = recursive ? flatt(list[idx]) : list[idx];
17584 j = -1;
17585 jlen = value.length;
17586 while (++j < jlen) {
17587 result[result.length] = value[j];
17588 }
17589 } else {
17590 result[result.length] = list[idx];
17591 }
17592 }
17593 return result;
17594 };
17595 };
17596
17597 var _reduce = function () {
17598 function _arrayReduce(xf, acc, list) {
17599 var idx = -1, len = list.length;
17600 while (++idx < len) {
17601 acc = xf['@@transducer/step'](acc, list[idx]);
17602 if (acc && acc['@@transducer/reduced']) {
17603 acc = acc['@@transducer/value'];
17604 break;
17605 }
17606 }
17607 return xf['@@transducer/result'](acc);
17608 }
17609 function _iterableReduce(xf, acc, iter) {
17610 var step = iter.next();
17611 while (!step.done) {
17612 acc = xf['@@transducer/step'](acc, step.value);
17613 if (acc && acc['@@transducer/reduced']) {
17614 acc = acc['@@transducer/value'];
17615 break;
17616 }
17617 step = iter.next();
17618 }
17619 return xf['@@transducer/result'](acc);
17620 }
17621 function _methodReduce(xf, acc, obj) {
17622 return xf['@@transducer/result'](obj.reduce(bind(xf['@@transducer/step'], xf), acc));
17623 }
17624 var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator';
17625 return function _reduce(fn, acc, list) {
17626 if (typeof fn === 'function') {
17627 fn = _xwrap(fn);
17628 }
17629 if (isArrayLike(list)) {
17630 return _arrayReduce(fn, acc, list);
17631 }
17632 if (typeof list.reduce === 'function') {
17633 return _methodReduce(fn, acc, list);
17634 }
17635 if (list[symIterator] != null) {
17636 return _iterableReduce(fn, acc, list[symIterator]());
17637 }
17638 if (typeof list.next === 'function') {
17639 return _iterableReduce(fn, acc, list);
17640 }
17641 throw new TypeError('reduce: list must be array or iterable');
17642 };
17643 }();
17644
17645 var _xall = function () {
17646 function XAll(f, xf) {
17647 this.xf = xf;
17648 this.f = f;
17649 this.all = true;
17650 }
17651 XAll.prototype['@@transducer/init'] = _xfBase.init;
17652 XAll.prototype['@@transducer/result'] = function (result) {
17653 if (this.all) {
17654 result = this.xf['@@transducer/step'](result, true);
17655 }
17656 return this.xf['@@transducer/result'](result);
17657 };
17658 XAll.prototype['@@transducer/step'] = function (result, input) {
17659 if (!this.f(input)) {
17660 this.all = false;
17661 result = _reduced(this.xf['@@transducer/step'](result, false));
17662 }
17663 return result;
17664 };
17665 return _curry2(function _xall(f, xf) {
17666 return new XAll(f, xf);
17667 });
17668 }();
17669
17670 var _xany = function () {
17671 function XAny(f, xf) {
17672 this.xf = xf;
17673 this.f = f;
17674 this.any = false;
17675 }
17676 XAny.prototype['@@transducer/init'] = _xfBase.init;
17677 XAny.prototype['@@transducer/result'] = function (result) {
17678 if (!this.any) {
17679 result = this.xf['@@transducer/step'](result, false);
17680 }
17681 return this.xf['@@transducer/result'](result);
17682 };
17683 XAny.prototype['@@transducer/step'] = function (result, input) {
17684 if (this.f(input)) {
17685 this.any = true;
17686 result = _reduced(this.xf['@@transducer/step'](result, true));
17687 }
17688 return result;
17689 };
17690 return _curry2(function _xany(f, xf) {
17691 return new XAny(f, xf);
17692 });
17693 }();
17694
17695 var _xdrop = function () {
17696 function XDrop(n, xf) {
17697 this.xf = xf;
17698 this.n = n;
17699 }
17700 XDrop.prototype['@@transducer/init'] = _xfBase.init;
17701 XDrop.prototype['@@transducer/result'] = _xfBase.result;
17702 XDrop.prototype.step = function (result, input) {
17703 if (this.n > 0) {
17704 this.n -= 1;
17705 return result;
17706 }
17707 return this.xf['@@transducer/step'](result, input);
17708 };
17709 return _curry2(function _xdrop(n, xf) {
17710 return new XDrop(n, xf);
17711 });
17712 }();
17713
17714 var _xdropWhile = function () {
17715 function XDropWhile(f, xf) {
17716 this.xf = xf;
17717 this.f = f;
17718 }
17719 XDropWhile.prototype['@@transducer/init'] = _xfBase.init;
17720 XDropWhile.prototype['@@transducer/result'] = _xfBase.result;
17721 XDropWhile.prototype['@@transducer/step'] = function (result, input) {
17722 if (this.f) {
17723 if (this.f(input)) {
17724 return result;
17725 }
17726 this.f = null;
17727 }
17728 return this.xf['@@transducer/step'](result, input);
17729 };
17730 return _curry2(function _xdropWhile(f, xf) {
17731 return new XDropWhile(f, xf);
17732 });
17733 }();
17734
17735 var _xgroupBy = function () {
17736 function XGroupBy(f, xf) {
17737 this.xf = xf;
17738 this.f = f;
17739 this.inputs = {};
17740 }
17741 XGroupBy.prototype['@@transducer/init'] = _xfBase.init;
17742 XGroupBy.prototype['@@transducer/result'] = function (result) {
17743 var key;
17744 for (key in this.inputs) {
17745 if (_has(key, this.inputs)) {
17746 result = this.xf['@@transducer/step'](result, this.inputs[key]);
17747 if (result['@@transducer/reduced']) {
17748 result = result['@@transducer/value'];
17749 break;
17750 }
17751 }
17752 }
17753 return this.xf['@@transducer/result'](result);
17754 };
17755 XGroupBy.prototype['@@transducer/step'] = function (result, input) {
17756 var key = this.f(input);
17757 this.inputs[key] = this.inputs[key] || [
17758 key,
17759 []
17760 ];
17761 this.inputs[key][1] = _append(input, this.inputs[key][1]);
17762 return result;
17763 };
17764 return _curry2(function _xgroupBy(f, xf) {
17765 return new XGroupBy(f, xf);
17766 });
17767 }();
17768
17769 /**
17770 * Returns `true` if all elements of the list match the predicate, `false` if there are any
17771 * that don't.
17772 *
17773 * Acts as a transducer if a transformer is given in list position.
17774 * @see R.transduce
17775 *
17776 * @func
17777 * @memberOf R
17778 * @category List
17779 * @sig (a -> Boolean) -> [a] -> Boolean
17780 * @param {Function} fn The predicate function.
17781 * @param {Array} list The array to consider.
17782 * @return {Boolean} `true` if the predicate is satisfied by every element, `false`
17783 * otherwise.
17784 * @example
17785 *
17786 * var lessThan2 = R.flip(R.lt)(2);
17787 * var lessThan3 = R.flip(R.lt)(3);
17788 * R.all(lessThan2)([1, 2]); //=> false
17789 * R.all(lessThan3)([1, 2]); //=> true
17790 */
17791 var all = _curry2(_dispatchable('all', _xall, _all));
17792
17793 /**
17794 * A function that returns the first argument if it's falsy otherwise the second
17795 * argument. Note that this is NOT short-circuited, meaning that if expressions
17796 * are passed they are both evaluated.
17797 *
17798 * Dispatches to the `and` method of the first argument if applicable.
17799 *
17800 * @func
17801 * @memberOf R
17802 * @category Logic
17803 * @sig * -> * -> *
17804 * @param {*} a any value
17805 * @param {*} b any other value
17806 * @return {*} the first argument if falsy otherwise the second argument.
17807 * @example
17808 *
17809 * R.and(false, true); //=> false
17810 * R.and(0, []); //=> 0
17811 * R.and(null, ''); => null
17812 */
17813 var and = _curry2(function and(a, b) {
17814 return _hasMethod('and', a) ? a.and(b) : a && b;
17815 });
17816
17817 /**
17818 * Returns `true` if at least one of elements of the list match the predicate, `false`
17819 * otherwise.
17820 *
17821 * Acts as a transducer if a transformer is given in list position.
17822 * @see R.transduce
17823 *
17824 * @func
17825 * @memberOf R
17826 * @category List
17827 * @sig (a -> Boolean) -> [a] -> Boolean
17828 * @param {Function} fn The predicate function.
17829 * @param {Array} list The array to consider.
17830 * @return {Boolean} `true` if the predicate is satisfied by at least one element, `false`
17831 * otherwise.
17832 * @example
17833 *
17834 * var lessThan0 = R.flip(R.lt)(0);
17835 * var lessThan2 = R.flip(R.lt)(2);
17836 * R.any(lessThan0)([1, 2]); //=> false
17837 * R.any(lessThan2)([1, 2]); //=> true
17838 */
17839 var any = _curry2(_dispatchable('any', _xany, _any));
17840
17841 /**
17842 * Returns a new list containing the contents of the given list, followed by the given
17843 * element.
17844 *
17845 * @func
17846 * @memberOf R
17847 * @category List
17848 * @sig a -> [a] -> [a]
17849 * @param {*} el The element to add to the end of the new list.
17850 * @param {Array} list The list whose contents will be added to the beginning of the output
17851 * list.
17852 * @return {Array} A new list containing the contents of the old list followed by `el`.
17853 * @example
17854 *
17855 * R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
17856 * R.append('tests', []); //=> ['tests']
17857 * R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
17858 */
17859 var append = _curry2(_append);
17860
17861 /**
17862 * Makes a shallow clone of an object, setting or overriding the nodes
17863 * required to create the given path, and placing the specific value at the
17864 * tail end of that path. Note that this copies and flattens prototype
17865 * properties onto the new object as well. All non-primitive properties
17866 * are copied by reference.
17867 *
17868 * @func
17869 * @memberOf R
17870 * @category Object
17871 * @sig [String] -> a -> {k: v} -> {k: v}
17872 * @param {Array} path the path to set
17873 * @param {*} val the new value
17874 * @param {Object} obj the object to clone
17875 * @return {Object} a new object similar to the original except along the specified path.
17876 * @example
17877 *
17878 * R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}
17879 */
17880 var assocPath = _curry3(_assocPath);
17881
17882 /**
17883 * Wraps a function of any arity (including nullary) in a function that accepts exactly 2
17884 * parameters. Any extraneous parameters will not be passed to the supplied function.
17885 *
17886 * @func
17887 * @memberOf R
17888 * @category Function
17889 * @sig (* -> c) -> (a, b -> c)
17890 * @param {Function} fn The function to wrap.
17891 * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
17892 * arity 2.
17893 * @example
17894 *
17895 * var takesThreeArgs = function(a, b, c) {
17896 * return [a, b, c];
17897 * };
17898 * takesThreeArgs.length; //=> 3
17899 * takesThreeArgs(1, 2, 3); //=> [1, 2, 3]
17900 *
17901 * var takesTwoArgs = R.binary(takesThreeArgs);
17902 * takesTwoArgs.length; //=> 2
17903 * // Only 2 arguments are passed to the wrapped function
17904 * takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
17905 */
17906 var binary = _curry1(function binary(fn) {
17907 return nAry(2, fn);
17908 });
17909
17910 /**
17911 * Creates a deep copy of the value which may contain (nested) `Array`s and
17912 * `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are
17913 * not copied, but assigned by their reference.
17914 *
17915 * @func
17916 * @memberOf R
17917 * @category Object
17918 * @sig {*} -> {*}
17919 * @param {*} value The object or array to clone
17920 * @return {*} A new object or array.
17921 * @example
17922 *
17923 * var objects = [{}, {}, {}];
17924 * var objectsClone = R.clone(objects);
17925 * objects[0] === objectsClone[0]; //=> false
17926 */
17927 var clone = _curry1(function clone(value) {
17928 return _baseCopy(value, [], []);
17929 });
17930
17931 /**
17932 * Creates a new function that runs each of the functions supplied as parameters in turn,
17933 * passing the return value of each function invocation to the next function invocation,
17934 * beginning with whatever arguments were passed to the initial invocation.
17935 *
17936 * Note that `compose` is a right-associative function, which means the functions provided
17937 * will be invoked in order from right to left. In the example `var h = compose(f, g)`,
17938 * the function `h` is equivalent to `f( g(x) )`, where `x` represents the arguments
17939 * originally passed to `h`.
17940 *
17941 * @func
17942 * @memberOf R
17943 * @category Function
17944 * @sig ((y -> z), (x -> y), ..., (b -> c), (a... -> b)) -> (a... -> z)
17945 * @param {...Function} functions A variable number of functions.
17946 * @return {Function} A new function which represents the result of calling each of the
17947 * input `functions`, passing the result of each function call to the next, from
17948 * right to left.
17949 * @example
17950 *
17951 * var triple = function(x) { return x * 3; };
17952 * var double = function(x) { return x * 2; };
17953 * var square = function(x) { return x * x; };
17954 * var squareThenDoubleThenTriple = R.compose(triple, double, square);
17955 *
17956 * //≅ triple(double(square(5)))
17957 * squareThenDoubleThenTriple(5); //=> 150
17958 */
17959 var compose = _createComposer(_compose);
17960
17961 /**
17962 * Creates a new lens that allows getting and setting values of nested properties, by
17963 * following each given lens in succession.
17964 *
17965 * Note that `composeL` is a right-associative function, which means the lenses provided
17966 * will be invoked in order from right to left.
17967 *
17968 * @func
17969 * @memberOf R
17970 * @category Function
17971 * @see R.lens
17972 * @sig ((y -> z), (x -> y), ..., (b -> c), (a -> b)) -> (a -> z)
17973 * @param {...Function} lenses A variable number of lenses.
17974 * @return {Function} A new lens which represents the result of calling each of the
17975 * input `lenses`, passing the result of each getter/setter as the source
17976 * to the next, from right to left.
17977 * @example
17978 *
17979 * var headLens = R.lensIndex(0);
17980 * var secondLens = R.lensIndex(1);
17981 * var xLens = R.lensProp('x');
17982 * var secondOfXOfHeadLens = R.composeL(secondLens, xLens, headLens);
17983 *
17984 * var source = [{x: [0, 1], y: [2, 3]}, {x: [4, 5], y: [6, 7]}];
17985 * secondOfXOfHeadLens(source); //=> 1
17986 * secondOfXOfHeadLens.set(123, source); //=> [{x: [0, 123], y: [2, 3]}, {x: [4, 5], y: [6, 7]}]
17987 */
17988 var composeL = function () {
17989 var idx = arguments.length - 1;
17990 var fn = arguments[idx];
17991 while (--idx >= 0) {
17992 fn = _composeL(arguments[idx], fn);
17993 }
17994 return fn;
17995 };
17996
17997 /**
17998 * Similar to `compose` but with automatic handling of promises (or, more
17999 * precisely, "thenables"). The behavior is identical to that of
18000 * compose() if all composed functions return something other than
18001 * promises (i.e., objects with a .then() method). If one of the function
18002 * returns a promise, however, then the next function in the composition
18003 * is called asynchronously, in the success callback of the promise, using
18004 * the resolved value as an input. Note that `composeP` is a right-
18005 * associative function, just like `compose`.
18006 *
18007 * @func
18008 * @memberOf R
18009 * @category Function
18010 * @sig ((y -> z), (x -> y), ..., (b -> c), (a... -> b)) -> (a... -> z)
18011 * @param {...Function} functions A variable number of functions.
18012 * @return {Function} A new function which represents the result of calling each of the
18013 * input `functions`, passing either the returned result or the asynchronously
18014 * resolved value) of each function call to the next, from right to left.
18015 * @example
18016 *
18017 * var Q = require('q');
18018 * var triple = function(x) { return x * 3; };
18019 * var double = function(x) { return x * 2; };
18020 * var squareAsync = function(x) { return Q.when(x * x); };
18021 * var squareAsyncThenDoubleThenTriple = R.composeP(triple, double, squareAsync);
18022 *
18023 * //≅ squareAsync(5).then(function(x) { return triple(double(x)) };
18024 * squareAsyncThenDoubleThenTriple(5)
18025 * .then(function(result) {
18026 * // result is 150
18027 * });
18028 */
18029 var composeP = _createComposer(_composeP);
18030
18031 /**
18032 * Returns a new list consisting of the elements of the first list followed by the elements
18033 * of the second.
18034 *
18035 * @func
18036 * @memberOf R
18037 * @category List
18038 * @sig [a] -> [a] -> [a]
18039 * @param {Array} list1 The first list to merge.
18040 * @param {Array} list2 The second set to merge.
18041 * @return {Array} A new array consisting of the contents of `list1` followed by the
18042 * contents of `list2`. If, instead of an Array for `list1`, you pass an
18043 * object with a `concat` method on it, `concat` will call `list1.concat`
18044 * and pass it the value of `list2`.
18045 *
18046 * @example
18047 *
18048 * R.concat([], []); //=> []
18049 * R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
18050 * R.concat('ABC', 'DEF'); // 'ABCDEF'
18051 */
18052 var concat = _curry2(function (set1, set2) {
18053 if (_isArray(set2)) {
18054 return _concat(set1, set2);
18055 } else if (_hasMethod('concat', set1)) {
18056 return set1.concat(set2);
18057 } else {
18058 throw new TypeError('can\'t concat ' + typeof set1);
18059 }
18060 });
18061
18062 /**
18063 * Returns `true` if the specified item is somewhere in the list, `false` otherwise.
18064 * Equivalent to `indexOf(a, list) >= 0`.
18065 *
18066 * Has `Object.is` semantics: `NaN` is considered equal to `NaN`; `0` and `-0`
18067 * are not considered equal.
18068 *
18069 * @func
18070 * @memberOf R
18071 * @category List
18072 * @sig a -> [a] -> Boolean
18073 * @param {Object} a The item to compare against.
18074 * @param {Array} list The array to consider.
18075 * @return {Boolean} `true` if the item is in the list, `false` otherwise.
18076 *
18077 * @example
18078 *
18079 * R.contains(3)([1, 2, 3]); //=> true
18080 * R.contains(4)([1, 2, 3]); //=> false
18081 * R.contains({})([{}, {}]); //=> false
18082 * var obj = {};
18083 * R.contains(obj)([{}, obj, {}]); //=> true
18084 */
18085 var contains = _curry2(_contains);
18086
18087 /**
18088 * Returns a curried equivalent of the provided function. The curried
18089 * function has two unusual capabilities. First, its arguments needn't
18090 * be provided one at a time. If `f` is a ternary function and `g` is
18091 * `R.curry(f)`, the following are equivalent:
18092 *
18093 * - `g(1)(2)(3)`
18094 * - `g(1)(2, 3)`
18095 * - `g(1, 2)(3)`
18096 * - `g(1, 2, 3)`
18097 *
18098 * Secondly, the special placeholder value `R.__` may be used to specify
18099 * "gaps", allowing partial application of any combination of arguments,
18100 * regardless of their positions. If `g` is as above and `_` is `R.__`,
18101 * the following are equivalent:
18102 *
18103 * - `g(1, 2, 3)`
18104 * - `g(_, 2, 3)(1)`
18105 * - `g(_, _, 3)(1)(2)`
18106 * - `g(_, _, 3)(1, 2)`
18107 * - `g(_, 2)(1)(3)`
18108 * - `g(_, 2)(1, 3)`
18109 * - `g(_, 2)(_, 3)(1)`
18110 *
18111 * @func
18112 * @memberOf R
18113 * @category Function
18114 * @sig (* -> a) -> (* -> a)
18115 * @param {Function} fn The function to curry.
18116 * @return {Function} A new, curried function.
18117 * @see R.curryN
18118 * @example
18119 *
18120 * var addFourNumbers = function(a, b, c, d) {
18121 * return a + b + c + d;
18122 * };
18123 *
18124 * var curriedAddFourNumbers = R.curry(addFourNumbers);
18125 * var f = curriedAddFourNumbers(1, 2);
18126 * var g = f(3);
18127 * g(4); //=> 10
18128 */
18129 var curry = _curry1(function curry(fn) {
18130 return curryN(fn.length, fn);
18131 });
18132
18133 /**
18134 * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
18135 *
18136 * @func
18137 * @memberOf R
18138 * @category Relation
18139 * @sig [a] -> [a] -> [a]
18140 * @param {Array} list1 The first list.
18141 * @param {Array} list2 The second list.
18142 * @return {Array} The elements in `list1` that are not in `list2`.
18143 * @see R.differenceWith
18144 * @example
18145 *
18146 * R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2]
18147 * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5]
18148 */
18149 var difference = _curry2(function difference(first, second) {
18150 var out = [];
18151 var idx = -1;
18152 var firstLen = first.length;
18153 while (++idx < firstLen) {
18154 if (!_contains(first[idx], second) && !_contains(first[idx], out)) {
18155 out[out.length] = first[idx];
18156 }
18157 }
18158 return out;
18159 });
18160
18161 /**
18162 * Makes a shallow clone of an object, omitting the property at the
18163 * given path. Note that this copies and flattens prototype properties
18164 * onto the new object as well. All non-primitive properties are copied
18165 * by reference.
18166 *
18167 * @func
18168 * @memberOf R
18169 * @category Object
18170 * @sig [String] -> {k: v} -> {k: v}
18171 * @param {Array} path the path to set
18172 * @param {Object} obj the object to clone
18173 * @return {Object} a new object without the property at path
18174 * @example
18175 *
18176 * R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}}
18177 */
18178 var dissocPath = _curry2(_dissocPath);
18179
18180 /**
18181 * Returns a list containing all but the first `n` elements of the given `list`.
18182 *
18183 * Acts as a transducer if a transformer is given in list position.
18184 * @see R.transduce
18185 *
18186 * @func
18187 * @memberOf R
18188 * @category List
18189 * @sig Number -> [a] -> [a]
18190 * @param {Number} n The number of elements of `list` to skip.
18191 * @param {Array} list The array to consider.
18192 * @return {Array} The last `n` elements of `list`.
18193 * @example
18194 *
18195 * R.drop(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7]
18196 */
18197 var drop = _curry2(_dispatchable('drop', _xdrop, function drop(n, list) {
18198 return n <= 0 ? list : _slice(list, n);
18199 }));
18200
18201 /**
18202 * Returns a new list containing the last `n` elements of a given list, passing each value
18203 * to the supplied predicate function, skipping elements while the predicate function returns
18204 * `true`. The predicate function is passed one argument: *(value)*.
18205 *
18206 * Acts as a transducer if a transformer is given in list position.
18207 * @see R.transduce
18208 *
18209 * @func
18210 * @memberOf R
18211 * @category List
18212 * @sig (a -> Boolean) -> [a] -> [a]
18213 * @param {Function} fn The function called per iteration.
18214 * @param {Array} list The collection to iterate over.
18215 * @return {Array} A new array.
18216 * @example
18217 *
18218 * var lteTwo = function(x) {
18219 * return x <= 2;
18220 * };
18221 *
18222 * R.dropWhile(lteTwo, [1, 2, 3, 4]); //=> [3, 4]
18223 */
18224 var dropWhile = _curry2(_dispatchable('dropWhile', _xdropWhile, function dropWhile(pred, list) {
18225 var idx = -1, len = list.length;
18226 while (++idx < len && pred(list[idx])) {
18227 }
18228 return _slice(list, idx);
18229 }));
18230
18231 /**
18232 * `empty` wraps any object in an array. This implementation is compatible with the
18233 * Fantasy-land Monoid spec, and will work with types that implement that spec.
18234 *
18235 * @func
18236 * @memberOf R
18237 * @category Function
18238 * @sig * -> []
18239 * @return {Array} An empty array.
18240 * @example
18241 *
18242 * R.empty([1,2,3,4,5]); //=> []
18243 */
18244 var empty = _curry1(function empty(x) {
18245 return _hasMethod('empty', x) ? x.empty() : [];
18246 });
18247
18248 /**
18249 * Returns a new list containing only those items that match a given predicate function.
18250 * The predicate function is passed one argument: *(value)*.
18251 *
18252 * Note that `R.filter` does not skip deleted or unassigned indices, unlike the native
18253 * `Array.prototype.filter` method. For more details on this behavior, see:
18254 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Description
18255 *
18256 * Acts as a transducer if a transformer is given in list position.
18257 * @see R.transduce
18258 *
18259 * @func
18260 * @memberOf R
18261 * @category List
18262 * @sig (a -> Boolean) -> [a] -> [a]
18263 * @param {Function} fn The function called per iteration.
18264 * @param {Array} list The collection to iterate over.
18265 * @return {Array} The new filtered array.
18266 * @example
18267 *
18268 * var isEven = function(n) {
18269 * return n % 2 === 0;
18270 * };
18271 * R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]
18272 */
18273 var filter = _curry2(_dispatchable('filter', _xfilter, _filter));
18274
18275 /**
18276 * Returns the first element of the list which matches the predicate, or `undefined` if no
18277 * element matches.
18278 *
18279 * Acts as a transducer if a transformer is given in list position.
18280 * @see R.transduce
18281 *
18282 * @func
18283 * @memberOf R
18284 * @category List
18285 * @sig (a -> Boolean) -> [a] -> a | undefined
18286 * @param {Function} fn The predicate function used to determine if the element is the
18287 * desired one.
18288 * @param {Array} list The array to consider.
18289 * @return {Object} The element found, or `undefined`.
18290 * @example
18291 *
18292 * var xs = [{a: 1}, {a: 2}, {a: 3}];
18293 * R.find(R.propEq('a', 2))(xs); //=> {a: 2}
18294 * R.find(R.propEq('a', 4))(xs); //=> undefined
18295 */
18296 var find = _curry2(_dispatchable('find', _xfind, function find(fn, list) {
18297 var idx = -1;
18298 var len = list.length;
18299 while (++idx < len) {
18300 if (fn(list[idx])) {
18301 return list[idx];
18302 }
18303 }
18304 }));
18305
18306 /**
18307 * Returns the index of the first element of the list which matches the predicate, or `-1`
18308 * if no element matches.
18309 *
18310 * Acts as a transducer if a transformer is given in list position.
18311 * @see R.transduce
18312 *
18313 * @func
18314 * @memberOf R
18315 * @category List
18316 * @sig (a -> Boolean) -> [a] -> Number
18317 * @param {Function} fn The predicate function used to determine if the element is the
18318 * desired one.
18319 * @param {Array} list The array to consider.
18320 * @return {Number} The index of the element found, or `-1`.
18321 * @example
18322 *
18323 * var xs = [{a: 1}, {a: 2}, {a: 3}];
18324 * R.findIndex(R.propEq('a', 2))(xs); //=> 1
18325 * R.findIndex(R.propEq('a', 4))(xs); //=> -1
18326 */
18327 var findIndex = _curry2(_dispatchable('findIndex', _xfindIndex, function findIndex(fn, list) {
18328 var idx = -1;
18329 var len = list.length;
18330 while (++idx < len) {
18331 if (fn(list[idx])) {
18332 return idx;
18333 }
18334 }
18335 return -1;
18336 }));
18337
18338 /**
18339 * Returns the last element of the list which matches the predicate, or `undefined` if no
18340 * element matches.
18341 *
18342 * Acts as a transducer if a transformer is given in list position.
18343 * @see R.transduce
18344 *
18345 * @func
18346 * @memberOf R
18347 * @category List
18348 * @sig (a -> Boolean) -> [a] -> a | undefined
18349 * @param {Function} fn The predicate function used to determine if the element is the
18350 * desired one.
18351 * @param {Array} list The array to consider.
18352 * @return {Object} The element found, or `undefined`.
18353 * @example
18354 *
18355 * var xs = [{a: 1, b: 0}, {a:1, b: 1}];
18356 * R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1}
18357 * R.findLast(R.propEq('a', 4))(xs); //=> undefined
18358 */
18359 var findLast = _curry2(_dispatchable('findLast', _xfindLast, function findLast(fn, list) {
18360 var idx = list.length;
18361 while (--idx >= 0) {
18362 if (fn(list[idx])) {
18363 return list[idx];
18364 }
18365 }
18366 }));
18367
18368 /**
18369 * Returns the index of the last element of the list which matches the predicate, or
18370 * `-1` if no element matches.
18371 *
18372 * Acts as a transducer if a transformer is given in list position.
18373 * @see R.transduce
18374 *
18375 * @func
18376 * @memberOf R
18377 * @category List
18378 * @sig (a -> Boolean) -> [a] -> Number
18379 * @param {Function} fn The predicate function used to determine if the element is the
18380 * desired one.
18381 * @param {Array} list The array to consider.
18382 * @return {Number} The index of the element found, or `-1`.
18383 * @example
18384 *
18385 * var xs = [{a: 1, b: 0}, {a:1, b: 1}];
18386 * R.findLastIndex(R.propEq('a', 1))(xs); //=> 1
18387 * R.findLastIndex(R.propEq('a', 4))(xs); //=> -1
18388 */
18389 var findLastIndex = _curry2(_dispatchable('findLastIndex', _xfindLastIndex, function findLastIndex(fn, list) {
18390 var idx = list.length;
18391 while (--idx >= 0) {
18392 if (fn(list[idx])) {
18393 return idx;
18394 }
18395 }
18396 return -1;
18397 }));
18398
18399 /**
18400 * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting
18401 * them in a new array, depth-first.
18402 *
18403 * @func
18404 * @memberOf R
18405 * @category List
18406 * @sig [a] -> [b]
18407 * @param {Array} list The array to consider.
18408 * @return {Array} The flattened list.
18409 * @example
18410 *
18411 * R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
18412 * //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
18413 */
18414 var flatten = _curry1(_makeFlat(true));
18415
18416 /**
18417 * Returns a new function much like the supplied one, except that the first two arguments'
18418 * order is reversed.
18419 *
18420 * @func
18421 * @memberOf R
18422 * @category Function
18423 * @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z)
18424 * @param {Function} fn The function to invoke with its first two parameters reversed.
18425 * @return {*} The result of invoking `fn` with its first two parameters' order reversed.
18426 * @example
18427 *
18428 * var mergeThree = function(a, b, c) {
18429 * return ([]).concat(a, b, c);
18430 * };
18431 *
18432 * mergeThree(1, 2, 3); //=> [1, 2, 3]
18433 *
18434 * R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]
18435 */
18436 var flip = _curry1(function flip(fn) {
18437 return curry(function (a, b) {
18438 var args = _slice(arguments);
18439 args[0] = b;
18440 args[1] = a;
18441 return fn.apply(this, args);
18442 });
18443 });
18444
18445 /**
18446 * Returns a list of function names of object's own and prototype functions
18447 *
18448 * @func
18449 * @memberOf R
18450 * @category Object
18451 * @sig {*} -> [String]
18452 * @param {Object} obj The objects with functions in it
18453 * @return {Array} A list of the object's own properties and prototype
18454 * properties that map to functions.
18455 * @example
18456 *
18457 * R.functionsIn(R); // returns list of ramda's own and prototype function names
18458 *
18459 * var F = function() { this.x = function(){}; this.y = 1; }
18460 * F.prototype.z = function() {};
18461 * F.prototype.a = 100;
18462 * R.functionsIn(new F()); //=> ["x", "z"]
18463 */
18464 var functionsIn = _curry1(_functionsWith(keysIn));
18465
18466 /**
18467 * Splits a list into sub-lists stored in an object, based on the result of calling a String-returning function
18468 * on each element, and grouping the results according to values returned.
18469 *
18470 * Acts as a transducer if a transformer is given in list position.
18471 * @see R.transduce
18472 *
18473 * @func
18474 * @memberOf R
18475 * @category List
18476 * @sig (a -> String) -> [a] -> {String: [a]}
18477 * @param {Function} fn Function :: a -> String
18478 * @param {Array} list The array to group
18479 * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements
18480 * that produced that key when passed to `fn`.
18481 * @example
18482 *
18483 * var byGrade = R.groupBy(function(student) {
18484 * var score = student.score;
18485 * return score < 65 ? 'F' :
18486 * score < 70 ? 'D' :
18487 * score < 80 ? 'C' :
18488 * score < 90 ? 'B' : 'A';
18489 * });
18490 * var students = [{name: 'Abby', score: 84},
18491 * {name: 'Eddy', score: 58},
18492 * // ...
18493 * {name: 'Jack', score: 69}];
18494 * byGrade(students);
18495 * // {
18496 * // 'A': [{name: 'Dianne', score: 99}],
18497 * // 'B': [{name: 'Abby', score: 84}]
18498 * // // ...,
18499 * // 'F': [{name: 'Eddy', score: 58}]
18500 * // }
18501 */
18502 var groupBy = _curry2(_dispatchable('groupBy', _xgroupBy, function groupBy(fn, list) {
18503 return _reduce(function (acc, elt) {
18504 var key = fn(elt);
18505 acc[key] = _append(elt, acc[key] || (acc[key] = []));
18506 return acc;
18507 }, {}, list);
18508 }));
18509
18510 /**
18511 * Returns the first element in a list.
18512 * In some libraries this function is named `first`.
18513 *
18514 * @func
18515 * @memberOf R
18516 * @category List
18517 * @sig [a] -> a
18518 * @param {Array} list The array to consider.
18519 * @return {*} The first element of the list, or `undefined` if the list is empty.
18520 * @example
18521 *
18522 * R.head(['fi', 'fo', 'fum']); //=> 'fi'
18523 */
18524 var head = nth(0);
18525
18526 /**
18527 * Inserts the supplied element into the list, at index `index`. _Note
18528 * that this is not destructive_: it returns a copy of the list with the changes.
18529 * <small>No lists have been harmed in the application of this function.</small>
18530 *
18531 * @func
18532 * @memberOf R
18533 * @category List
18534 * @sig Number -> a -> [a] -> [a]
18535 * @param {Number} index The position to insert the element
18536 * @param {*} elt The element to insert into the Array
18537 * @param {Array} list The list to insert into
18538 * @return {Array} A new Array with `elt` inserted at `index`.
18539 * @example
18540 *
18541 * R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4]
18542 */
18543 var insert = _curry3(function insert(idx, elt, list) {
18544 idx = idx < list.length && idx >= 0 ? idx : list.length;
18545 return _concat(_append(elt, _slice(list, 0, idx)), _slice(list, idx));
18546 });
18547
18548 /**
18549 * Combines two lists into a set (i.e. no duplicates) composed of those
18550 * elements common to both lists. Duplication is determined according
18551 * to the value returned by applying the supplied predicate to two list
18552 * elements.
18553 *
18554 * @func
18555 * @memberOf R
18556 * @category Relation
18557 * @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
18558 * @param {Function} pred A predicate function that determines whether
18559 * the two supplied elements are equal.
18560 * @param {Array} list1 One list of items to compare
18561 * @param {Array} list2 A second list of items to compare
18562 * @see R.intersection
18563 * @return {Array} A new list containing those elements common to both lists.
18564 * @example
18565 *
18566 * var buffaloSpringfield = [
18567 * {id: 824, name: 'Richie Furay'},
18568 * {id: 956, name: 'Dewey Martin'},
18569 * {id: 313, name: 'Bruce Palmer'},
18570 * {id: 456, name: 'Stephen Stills'},
18571 * {id: 177, name: 'Neil Young'}
18572 * ];
18573 * var csny = [
18574 * {id: 204, name: 'David Crosby'},
18575 * {id: 456, name: 'Stephen Stills'},
18576 * {id: 539, name: 'Graham Nash'},
18577 * {id: 177, name: 'Neil Young'}
18578 * ];
18579 *
18580 * var sameId = function(o1, o2) {return o1.id === o2.id;};
18581 *
18582 * R.intersectionWith(sameId, buffaloSpringfield, csny);
18583 * //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}]
18584 */
18585 var intersectionWith = _curry3(function intersectionWith(pred, list1, list2) {
18586 var results = [], idx = -1;
18587 while (++idx < list1.length) {
18588 if (_containsWith(pred, list1[idx], list2)) {
18589 results[results.length] = list1[idx];
18590 }
18591 }
18592 return uniqWith(pred, results);
18593 });
18594
18595 /**
18596 * Creates a new list with the separator interposed between elements.
18597 *
18598 * @func
18599 * @memberOf R
18600 * @category List
18601 * @sig a -> [a] -> [a]
18602 * @param {*} separator The element to add to the list.
18603 * @param {Array} list The list to be interposed.
18604 * @return {Array} The new list.
18605 * @example
18606 *
18607 * R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']
18608 */
18609 var intersperse = _curry2(_checkForMethod('intersperse', function intersperse(separator, list) {
18610 var out = [];
18611 var idx = -1;
18612 var length = list.length;
18613 while (++idx < length) {
18614 if (idx === length - 1) {
18615 out.push(list[idx]);
18616 } else {
18617 out.push(list[idx], separator);
18618 }
18619 }
18620 return out;
18621 }));
18622
18623 /**
18624 * Returns the result of applying `obj[methodName]` to `args`.
18625 *
18626 * @func
18627 * @memberOf R
18628 * @category Object
18629 * @sig String -> [*] -> Object -> *
18630 * @param {String} methodName
18631 * @param {Array} args
18632 * @param {Object} obj
18633 * @return {*}
18634 * @example
18635 *
18636 * // toBinary :: Number -> String
18637 * var toBinary = R.invoke('toString', [2])
18638 *
18639 * toBinary(42); //=> '101010'
18640 * toBinary(63); //=> '111111'
18641 */
18642 var invoke = curry(function invoke(methodName, args, obj) {
18643 return obj[methodName].apply(obj, args);
18644 });
18645
18646 /**
18647 * Turns a named method with a specified arity into a function
18648 * that can be called directly supplied with arguments and a target object.
18649 *
18650 * The returned function is curried and accepts `len + 1` parameters where
18651 * the final parameter is the target object.
18652 *
18653 * @func
18654 * @memberOf R
18655 * @category Function
18656 * @sig (Number, String) -> (a... -> c -> b)
18657 * @param {Number} len Number of arguments the returned function should take
18658 * before the target object.
18659 * @param {Function} method Name of the method to call.
18660 * @return {Function} A new curried function.
18661 * @example
18662 *
18663 * var sliceFrom = R.invoker(1, 'slice');
18664 * sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'
18665 * var sliceFrom6 = R.invoker(2, 'slice', 6);
18666 * sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'
18667 */
18668 var invoker = curry(function invoker(arity, method) {
18669 var initialArgs = _slice(arguments, 2);
18670 var len = arity - initialArgs.length;
18671 return curryN(len + 1, function () {
18672 var target = arguments[len];
18673 var args = initialArgs.concat(_slice(arguments, 0, len));
18674 return target[method].apply(target, args);
18675 });
18676 });
18677
18678 /**
18679 * Returns a string made by inserting the `separator` between each
18680 * element and concatenating all the elements into a single string.
18681 *
18682 * @func
18683 * @memberOf R
18684 * @category List
18685 * @sig String -> [a] -> String
18686 * @param {Number|String} separator The string used to separate the elements.
18687 * @param {Array} xs The elements to join into a string.
18688 * @return {String} str The string made by concatenating `xs` with `separator`.
18689 * @example
18690 *
18691 * var spacer = R.join(' ');
18692 * spacer(['a', 2, 3.4]); //=> 'a 2 3.4'
18693 * R.join('|', [1, 2, 3]); //=> '1|2|3'
18694 */
18695 var join = invoker(1, 'join');
18696
18697 /**
18698 * Returns a list containing the names of all the enumerable own
18699 * properties of the supplied object.
18700 * Note that the order of the output array is not guaranteed to be
18701 * consistent across different JS platforms.
18702 *
18703 * @func
18704 * @memberOf R
18705 * @category Object
18706 * @sig {k: v} -> [k]
18707 * @param {Object} obj The object to extract properties from
18708 * @return {Array} An array of the object's own properties.
18709 * @example
18710 *
18711 * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
18712 */
18713 // cover IE < 9 keys issues
18714 var keys = function () {
18715 // cover IE < 9 keys issues
18716 var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString');
18717 var nonEnumerableProps = [
18718 'constructor',
18719 'valueOf',
18720 'isPrototypeOf',
18721 'toString',
18722 'propertyIsEnumerable',
18723 'hasOwnProperty',
18724 'toLocaleString'
18725 ];
18726 return _curry1(function keys(obj) {
18727 if (Object(obj) !== obj) {
18728 return [];
18729 }
18730 if (Object.keys) {
18731 return Object.keys(obj);
18732 }
18733 var prop, ks = [], nIdx;
18734 for (prop in obj) {
18735 if (_has(prop, obj)) {
18736 ks[ks.length] = prop;
18737 }
18738 }
18739 if (hasEnumBug) {
18740 nIdx = nonEnumerableProps.length;
18741 while (--nIdx >= 0) {
18742 prop = nonEnumerableProps[nIdx];
18743 if (_has(prop, obj) && !_contains(prop, ks)) {
18744 ks[ks.length] = prop;
18745 }
18746 }
18747 }
18748 return ks;
18749 });
18750 }();
18751
18752 /**
18753 * Returns the last element from a list.
18754 *
18755 * @func
18756 * @memberOf R
18757 * @category List
18758 * @sig [a] -> a
18759 * @param {Array} list The array to consider.
18760 * @return {*} The last element of the list, or `undefined` if the list is empty.
18761 * @example
18762 *
18763 * R.last(['fi', 'fo', 'fum']); //=> 'fum'
18764 */
18765 var last = nth(-1);
18766
18767 /**
18768 * Creates a lens that will focus on index `n` of the source array.
18769 *
18770 * @func
18771 * @memberOf R
18772 * @category List
18773 * @see R.lens
18774 * @sig Number -> (a -> b)
18775 * @param {Number} n The index of the array that the returned lens will focus on.
18776 * @return {Function} the returned function has `set` and `map` properties that are
18777 * also curried functions.
18778 * @example
18779 *
18780 * var headLens = R.lensIndex(0);
18781 * headLens([10, 20, 30, 40]); //=> 10
18782 * headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40]
18783 * headLens.map(function(x) { return x + 1; }, [10, 20, 30, 40]); //=> [11, 20, 30, 40]
18784 */
18785 var lensIndex = function lensIndex(n) {
18786 return lens(nth(n), function (x, xs) {
18787 return _slice(xs, 0, n).concat([x], _slice(xs, n + 1));
18788 });
18789 };
18790
18791 /**
18792 * Creates a lens that will focus on property `k` of the source object.
18793 *
18794 * @func
18795 * @memberOf R
18796 * @category Object
18797 * @see R.lens
18798 * @sig String -> (a -> b)
18799 * @param {String} k A string that represents a property to focus on.
18800 * @return {Function} the returned function has `set` and `map` properties that are
18801 * also curried functions.
18802 * @example
18803 *
18804 * var phraseLens = R.lensProp('phrase');
18805 * var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'};
18806 * var obj2 = { phrase: "What's all this, then?"};
18807 * phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!'
18808 * phraseLens(obj2); // => "What's all this, then?"
18809 * phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'}
18810 * phraseLens.map(R.toUpper, obj2); //=> { phrase: "WHAT'S ALL THIS, THEN?"}
18811 */
18812 var lensProp = function (k) {
18813 return lens(prop(k), assoc(k));
18814 };
18815
18816 /**
18817 * Returns a new list, constructed by applying the supplied function to every element of the
18818 * supplied list.
18819 *
18820 * Note: `R.map` does not skip deleted or unassigned indices (sparse arrays), unlike the
18821 * native `Array.prototype.map` method. For more details on this behavior, see:
18822 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
18823 *
18824 * Acts as a transducer if a transformer is given in list position.
18825 * @see R.transduce
18826 *
18827 * @func
18828 * @memberOf R
18829 * @category List
18830 * @sig (a -> b) -> [a] -> [b]
18831 * @param {Function} fn The function to be called on every element of the input `list`.
18832 * @param {Array} list The list to be iterated over.
18833 * @return {Array} The new list.
18834 * @example
18835 *
18836 * var double = function(x) {
18837 * return x * 2;
18838 * };
18839 *
18840 * R.map(double, [1, 2, 3]); //=> [2, 4, 6]
18841 */
18842 var map = _curry2(_dispatchable('map', _xmap, _map));
18843
18844 /**
18845 * Map, but for objects. Creates an object with the same keys as `obj` and values
18846 * generated by running each property of `obj` through `fn`. `fn` is passed one argument:
18847 * *(value)*.
18848 *
18849 * @func
18850 * @memberOf R
18851 * @category Object
18852 * @sig (v -> v) -> {k: v} -> {k: v}
18853 * @param {Function} fn A function called for each property in `obj`. Its return value will
18854 * become a new property on the return object.
18855 * @param {Object} obj The object to iterate over.
18856 * @return {Object} A new object with the same keys as `obj` and values that are the result
18857 * of running each property through `fn`.
18858 * @example
18859 *
18860 * var values = { x: 1, y: 2, z: 3 };
18861 * var double = function(num) {
18862 * return num * 2;
18863 * };
18864 *
18865 * R.mapObj(double, values); //=> { x: 2, y: 4, z: 6 }
18866 */
18867 var mapObj = _curry2(function mapObject(fn, obj) {
18868 return _reduce(function (acc, key) {
18869 acc[key] = fn(obj[key]);
18870 return acc;
18871 }, {}, keys(obj));
18872 });
18873
18874 /**
18875 * Like `mapObj`, but but passes additional arguments to the predicate function. The
18876 * predicate function is passed three arguments: *(value, key, obj)*.
18877 *
18878 * @func
18879 * @memberOf R
18880 * @category Object
18881 * @sig (v, k, {k: v} -> v) -> {k: v} -> {k: v}
18882 * @param {Function} fn A function called for each property in `obj`. Its return value will
18883 * become a new property on the return object.
18884 * @param {Object} obj The object to iterate over.
18885 * @return {Object} A new object with the same keys as `obj` and values that are the result
18886 * of running each property through `fn`.
18887 * @example
18888 *
18889 * var values = { x: 1, y: 2, z: 3 };
18890 * var prependKeyAndDouble = function(num, key, obj) {
18891 * return key + (num * 2);
18892 * };
18893 *
18894 * R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' }
18895 */
18896 var mapObjIndexed = _curry2(function mapObjectIndexed(fn, obj) {
18897 return _reduce(function (acc, key) {
18898 acc[key] = fn(obj[key], key, obj);
18899 return acc;
18900 }, {}, keys(obj));
18901 });
18902
18903 /**
18904 * Tests a regular expression against a String
18905 *
18906 * @func
18907 * @memberOf R
18908 * @category String
18909 * @sig RegExp -> String -> [String] | null
18910 * @param {RegExp} rx A regular expression.
18911 * @param {String} str The string to match against
18912 * @return {Array} The list of matches, or null if no matches found.
18913 * @see R.invoker
18914 * @example
18915 *
18916 * R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na']
18917 */
18918 var match = invoker(1, 'match');
18919
18920 /**
18921 * Determines the largest of a list of numbers (or elements that can be cast to numbers)
18922 *
18923 * @func
18924 * @memberOf R
18925 * @category Math
18926 * @sig [Number] -> Number
18927 * @see R.maxBy
18928 * @param {Array} list A list of numbers
18929 * @return {Number} The greatest number in the list.
18930 * @example
18931 *
18932 * R.max([7, 3, 9, 2, 4, 9, 3]); //=> 9
18933 */
18934 var max = _createMaxMin(_gt, -Infinity);
18935
18936 /**
18937 * Determines the smallest of a list of numbers (or elements that can be cast to numbers)
18938 *
18939 * @func
18940 * @memberOf R
18941 * @category Math
18942 * @sig [Number] -> Number
18943 * @param {Array} list A list of numbers
18944 * @return {Number} The greatest number in the list.
18945 * @see R.minBy
18946 * @example
18947 *
18948 * R.min([7, 3, 9, 2, 4, 9, 3]); //=> 2
18949 */
18950 var min = _createMaxMin(_lt, Infinity);
18951
18952 /**
18953 * Returns `true` if no elements of the list match the predicate,
18954 * `false` otherwise.
18955 *
18956 * @func
18957 * @memberOf R
18958 * @category List
18959 * @sig (a -> Boolean) -> [a] -> Boolean
18960 * @param {Function} fn The predicate function.
18961 * @param {Array} list The array to consider.
18962 * @return {Boolean} `true` if the predicate is not satisfied by every element, `false` otherwise.
18963 * @example
18964 *
18965 * R.none(R.isNaN, [1, 2, 3]); //=> true
18966 * R.none(R.isNaN, [1, 2, 3, NaN]); //=> false
18967 */
18968 var none = _curry2(_complement(_dispatchable('any', _xany, _any)));
18969
18970 /**
18971 * A function that returns the first truthy of two arguments otherwise the
18972 * last argument. Note that this is NOT short-circuited, meaning that if
18973 * expressions are passed they are both evaluated.
18974 *
18975 * Dispatches to the `or` method of the first argument if applicable.
18976 *
18977 * @func
18978 * @memberOf R
18979 * @category Logic
18980 * @sig * -> * -> *
18981 * @param {*} a any value
18982 * @param {*} b any other value
18983 * @return {*} the first truthy argument, otherwise the last argument.
18984 * @example
18985 *
18986 * R.or(false, true); //=> true
18987 * R.or(0, []); //=> []
18988 * R.or(null, ''); => ''
18989 */
18990 var or = _curry2(function or(a, b) {
18991 return _hasMethod('or', a) ? a.or(b) : a || b;
18992 });
18993
18994 /**
18995 * Accepts as its arguments a function and any number of values and returns a function that,
18996 * when invoked, calls the original function with all of the values prepended to the
18997 * original function's arguments list. In some libraries this function is named `applyLeft`.
18998 *
18999 * @func
19000 * @memberOf R
19001 * @category Function
19002 * @sig (a -> b -> ... -> i -> j -> ... -> m -> n) -> a -> b-> ... -> i -> (j -> ... -> m -> n)
19003 * @param {Function} fn The function to invoke.
19004 * @param {...*} [args] Arguments to prepend to `fn` when the returned function is invoked.
19005 * @return {Function} A new function wrapping `fn`. When invoked, it will call `fn`
19006 * with `args` prepended to `fn`'s arguments list.
19007 * @example
19008 *
19009 * var multiply = function(a, b) { return a * b; };
19010 * var double = R.partial(multiply, 2);
19011 * double(2); //=> 4
19012 *
19013 * var greet = function(salutation, title, firstName, lastName) {
19014 * return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
19015 * };
19016 * var sayHello = R.partial(greet, 'Hello');
19017 * var sayHelloToMs = R.partial(sayHello, 'Ms.');
19018 * sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!'
19019 */
19020 var partial = curry(_createPartialApplicator(_concat));
19021
19022 /**
19023 * Accepts as its arguments a function and any number of values and returns a function that,
19024 * when invoked, calls the original function with all of the values appended to the original
19025 * function's arguments list.
19026 *
19027 * Note that `partialRight` is the opposite of `partial`: `partialRight` fills `fn`'s arguments
19028 * from the right to the left. In some libraries this function is named `applyRight`.
19029 *
19030 * @func
19031 * @memberOf R
19032 * @category Function
19033 * @sig (a -> b-> ... -> i -> j -> ... -> m -> n) -> j -> ... -> m -> n -> (a -> b-> ... -> i)
19034 * @param {Function} fn The function to invoke.
19035 * @param {...*} [args] Arguments to append to `fn` when the returned function is invoked.
19036 * @return {Function} A new function wrapping `fn`. When invoked, it will call `fn` with
19037 * `args` appended to `fn`'s arguments list.
19038 * @example
19039 *
19040 * var greet = function(salutation, title, firstName, lastName) {
19041 * return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
19042 * };
19043 * var greetMsJaneJones = R.partialRight(greet, 'Ms.', 'Jane', 'Jones');
19044 *
19045 * greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!'
19046 */
19047 var partialRight = curry(_createPartialApplicator(flip(_concat)));
19048
19049 /**
19050 * Takes a predicate and a list and returns the pair of lists of
19051 * elements which do and do not satisfy the predicate, respectively.
19052 *
19053 * @func
19054 * @memberOf R
19055 * @category List
19056 * @sig (a -> Boolean) -> [a] -> [[a],[a]]
19057 * @param {Function} pred A predicate to determine which array the element belongs to.
19058 * @param {Array} list The array to partition.
19059 * @return {Array} A nested array, containing first an array of elements that satisfied the predicate,
19060 * and second an array of elements that did not satisfy.
19061 * @example
19062 *
19063 * R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']);
19064 * //=> [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ]
19065 */
19066 var partition = _curry2(function partition(pred, list) {
19067 return _reduce(function (acc, elt) {
19068 var xs = acc[pred(elt) ? 0 : 1];
19069 xs[xs.length] = elt;
19070 return acc;
19071 }, [
19072 [],
19073 []
19074 ], list);
19075 });
19076
19077 /**
19078 * Creates a new function that runs each of the functions supplied as parameters in turn,
19079 * passing the return value of each function invocation to the next function invocation,
19080 * beginning with whatever arguments were passed to the initial invocation.
19081 *
19082 * `pipe` is the mirror version of `compose`. `pipe` is left-associative, which means that
19083 * each of the functions provided is executed in order from left to right.
19084 *
19085 * In some libraries this function is named `sequence`.
19086 * @func
19087 * @memberOf R
19088 * @category Function
19089 * @sig ((a... -> b), (b -> c), ..., (x -> y), (y -> z)) -> (a... -> z)
19090 * @param {...Function} functions A variable number of functions.
19091 * @return {Function} A new function which represents the result of calling each of the
19092 * input `functions`, passing the result of each function call to the next, from
19093 * left to right.
19094 * @example
19095 *
19096 * var triple = function(x) { return x * 3; };
19097 * var double = function(x) { return x * 2; };
19098 * var square = function(x) { return x * x; };
19099 * var squareThenDoubleThenTriple = R.pipe(square, double, triple);
19100 *
19101 * //≅ triple(double(square(5)))
19102 * squareThenDoubleThenTriple(5); //=> 150
19103 */
19104 var pipe = function pipe() {
19105 return compose.apply(this, reverse(arguments));
19106 };
19107
19108 /**
19109 * Creates a new lens that allows getting and setting values of nested properties, by
19110 * following each given lens in succession.
19111 *
19112 * `pipeL` is the mirror version of `composeL`. `pipeL` is left-associative, which means that
19113 * each of the functions provided is executed in order from left to right.
19114 *
19115 * @func
19116 * @memberOf R
19117 * @category Function
19118 * @see R.lens
19119 * @sig ((a -> b), (b -> c), ..., (x -> y), (y -> z)) -> (a -> z)
19120 * @param {...Function} lenses A variable number of lenses.
19121 * @return {Function} A new lens which represents the result of calling each of the
19122 * input `lenses`, passing the result of each getter/setter as the source
19123 * to the next, from right to left.
19124 * @example
19125 *
19126 * var headLens = R.lensIndex(0);
19127 * var secondLens = R.lensIndex(1);
19128 * var xLens = R.lensProp('x');
19129 * var headThenXThenSecondLens = R.pipeL(headLens, xLens, secondLens);
19130 *
19131 * var source = [{x: [0, 1], y: [2, 3]}, {x: [4, 5], y: [6, 7]}];
19132 * headThenXThenSecondLens(source); //=> 1
19133 * headThenXThenSecondLens.set(123, source); //=> [{x: [0, 123], y: [2, 3]}, {x: [4, 5], y: [6, 7]}]
19134 */
19135 var pipeL = compose(apply(composeL), unapply(reverse));
19136
19137 /**
19138 * Creates a new function that runs each of the functions supplied as parameters in turn,
19139 * passing to the next function invocation either the value returned by the previous
19140 * function or the resolved value if the returned value is a promise. In other words,
19141 * if some of the functions in the sequence return promises, `pipeP` pipes the values
19142 * asynchronously. If none of the functions return promises, the behavior is the same as
19143 * that of `pipe`.
19144 *
19145 * `pipeP` is the mirror version of `composeP`. `pipeP` is left-associative, which means that
19146 * each of the functions provided is executed in order from left to right.
19147 *
19148 * @func
19149 * @memberOf R
19150 * @category Function
19151 * @sig ((a... -> b), (b -> c), ..., (x -> y), (y -> z)) -> (a... -> z)
19152 * @param {...Function} functions A variable number of functions.
19153 * @return {Function} A new function which represents the result of calling each of the
19154 * input `functions`, passing either the returned result or the asynchronously
19155 * resolved value) of each function call to the next, from left to right.
19156 * @example
19157 *
19158 * var Q = require('q');
19159 * var triple = function(x) { return x * 3; };
19160 * var double = function(x) { return x * 2; };
19161 * var squareAsync = function(x) { return Q.when(x * x); };
19162 * var squareAsyncThenDoubleThenTriple = R.pipeP(squareAsync, double, triple);
19163 *
19164 * //≅ squareAsync(5).then(function(x) { return triple(double(x)) };
19165 * squareAsyncThenDoubleThenTriple(5)
19166 * .then(function(result) {
19167 * // result is 150
19168 * });
19169 */
19170 var pipeP = function pipeP() {
19171 return composeP.apply(this, reverse(arguments));
19172 };
19173
19174 /**
19175 * Returns a single item by iterating through the list, successively calling the iterator
19176 * function and passing it an accumulator value and the current value from the array, and
19177 * then passing the result to the next call.
19178 *
19179 * The iterator function receives two values: *(acc, value)*
19180 *
19181 * Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike
19182 * the native `Array.prototype.reduce` method. For more details on this behavior, see:
19183 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
19184 *
19185 * @func
19186 * @memberOf R
19187 * @category List
19188 * @sig (a,b -> a) -> a -> [b] -> a
19189 * @param {Function} fn The iterator function. Receives two values, the accumulator and the
19190 * current element from the array.
19191 * @param {*} acc The accumulator value.
19192 * @param {Array} list The list to iterate over.
19193 * @return {*} The final, accumulated value.
19194 * @example
19195 *
19196 * var numbers = [1, 2, 3];
19197 * var add = function(a, b) {
19198 * return a + b;
19199 * };
19200 *
19201 * R.reduce(add, 10, numbers); //=> 16
19202 */
19203 var reduce = _curry3(_reduce);
19204
19205 /**
19206 * Similar to `filter`, except that it keeps only values for which the given predicate
19207 * function returns falsy. The predicate function is passed one argument: *(value)*.
19208 *
19209 * Acts as a transducer if a transformer is given in list position.
19210 * @see R.transduce
19211 *
19212 * @func
19213 * @memberOf R
19214 * @category List
19215 * @sig (a -> Boolean) -> [a] -> [a]
19216 * @param {Function} fn The function called per iteration.
19217 * @param {Array} list The collection to iterate over.
19218 * @return {Array} The new filtered array.
19219 * @example
19220 *
19221 * var isOdd = function(n) {
19222 * return n % 2 === 1;
19223 * };
19224 * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
19225 */
19226 var reject = _curry2(function reject(fn, list) {
19227 return filter(_complement(fn), list);
19228 });
19229
19230 /**
19231 * Returns a fixed list of size `n` containing a specified identical value.
19232 *
19233 * @func
19234 * @memberOf R
19235 * @category List
19236 * @sig a -> n -> [a]
19237 * @param {*} value The value to repeat.
19238 * @param {Number} n The desired size of the output list.
19239 * @return {Array} A new array containing `n` `value`s.
19240 * @example
19241 *
19242 * R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi']
19243 *
19244 * var obj = {};
19245 * var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}]
19246 * repeatedObjs[0] === repeatedObjs[1]; //=> true
19247 */
19248 var repeat = _curry2(function repeat(value, n) {
19249 return times(always(value), n);
19250 });
19251
19252 /**
19253 * Returns a list containing the elements of `xs` from `fromIndex` (inclusive)
19254 * to `toIndex` (exclusive).
19255 *
19256 * @func
19257 * @memberOf R
19258 * @category List
19259 * @sig Number -> Number -> [a] -> [a]
19260 * @param {Number} fromIndex The start index (inclusive).
19261 * @param {Number} toIndex The end index (exclusive).
19262 * @param {Array} xs The list to take elements from.
19263 * @return {Array} The slice of `xs` from `fromIndex` to `toIndex`.
19264 * @example
19265 *
19266 * var xs = R.range(0, 10);
19267 * R.slice(2, 5)(xs); //=> [2, 3, 4]
19268 */
19269 var slice = _curry3(_checkForMethod('slice', function slice(fromIndex, toIndex, xs) {
19270 return Array.prototype.slice.call(xs, fromIndex, toIndex);
19271 }));
19272
19273 /**
19274 * Splits a string into an array of strings based on the given
19275 * separator.
19276 *
19277 * @func
19278 * @memberOf R
19279 * @category String
19280 * @sig String -> String -> [String]
19281 * @param {String} sep The separator string.
19282 * @param {String} str The string to separate into an array.
19283 * @return {Array} The array of strings from `str` separated by `str`.
19284 * @example
19285 *
19286 * var pathComponents = R.split('/');
19287 * R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node']
19288 *
19289 * R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd']
19290 */
19291 var split = invoker(1, 'split');
19292
19293 /**
19294 * Returns a string containing the characters of `str` from `fromIndex`
19295 * (inclusive) to `toIndex` (exclusive).
19296 *
19297 * @func
19298 * @memberOf R
19299 * @category String
19300 * @sig Number -> Number -> String -> String
19301 * @param {Number} fromIndex The start index (inclusive).
19302 * @param {Number} toIndex The end index (exclusive).
19303 * @param {String} str The string to slice.
19304 * @return {String}
19305 * @see R.slice
19306 * @example
19307 *
19308 * R.substring(2, 5, 'abcdefghijklm'); //=> 'cde'
19309 */
19310 var substring = slice;
19311
19312 /**
19313 * Returns a string containing the characters of `str` from `fromIndex`
19314 * (inclusive) to the end of `str`.
19315 *
19316 * @func
19317 * @memberOf R
19318 * @category String
19319 * @sig Number -> String -> String
19320 * @param {Number} fromIndex
19321 * @param {String} str
19322 * @return {String}
19323 * @example
19324 *
19325 * R.substringFrom(3, 'Ramda'); //=> 'da'
19326 * R.substringFrom(-2, 'Ramda'); //=> 'da'
19327 */
19328 var substringFrom = substring(__, Infinity);
19329
19330 /**
19331 * Returns a string containing the first `toIndex` characters of `str`.
19332 *
19333 * @func
19334 * @memberOf R
19335 * @category String
19336 * @sig Number -> String -> String
19337 * @param {Number} toIndex
19338 * @param {String} str
19339 * @return {String}
19340 * @example
19341 *
19342 * R.substringTo(3, 'Ramda'); //=> 'Ram'
19343 * R.substringTo(-2, 'Ramda'); //=> 'Ram'
19344 */
19345 var substringTo = substring(0);
19346
19347 /**
19348 * Adds together all the elements of a list.
19349 *
19350 * @func
19351 * @memberOf R
19352 * @category Math
19353 * @sig [Number] -> Number
19354 * @param {Array} list An array of numbers
19355 * @return {Number} The sum of all the numbers in the list.
19356 * @see reduce
19357 * @example
19358 *
19359 * R.sum([2,4,6,8,100,1]); //=> 121
19360 */
19361 var sum = reduce(_add, 0);
19362
19363 /**
19364 * Returns all but the first element of a list. If the list provided has the `tail` method,
19365 * it will instead return `list.tail()`.
19366 *
19367 * @func
19368 * @memberOf R
19369 * @category List
19370 * @sig [a] -> [a]
19371 * @param {Array} list The array to consider.
19372 * @return {Array} A new array containing all but the first element of the input list, or an
19373 * empty list if the input list is empty.
19374 * @example
19375 *
19376 * R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum']
19377 */
19378 var tail = _checkForMethod('tail', function (list) {
19379 return _slice(list, 1);
19380 });
19381
19382 /**
19383 * Returns a new list containing the first `n` elements of the given list. If
19384 * `n > * list.length`, returns a list of `list.length` elements.
19385 *
19386 * Acts as a transducer if a transformer is given in list position.
19387 * @see R.transduce
19388 *
19389 * @func
19390 * @memberOf R
19391 * @category List
19392 * @sig Number -> [a] -> [a]
19393 * @param {Number} n The number of elements to return.
19394 * @param {Array} list The array to query.
19395 * @return {Array} A new array containing the first elements of `list`.
19396 * @example
19397 *
19398 * R.take(3,[1,2,3,4,5]); //=> [1,2,3]
19399 *
19400 * var members= [ "Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis","Joe Morello","Norman Bates",
19401 * "Eugene Wright","Gerry Mulligan","Jack Six","Alan Dawson","Darius Brubeck","Chris Brubeck",
19402 * "Dan Brubeck","Bobby Militello","Michael Moore","Randy Jones"];
19403 * var takeFive = R.take(5);
19404 * takeFive(members); //=> ["Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis"]
19405 */
19406 var take = _curry2(_dispatchable('take', _xtake, function take(n, list) {
19407 return _slice(list, 0, n);
19408 }));
19409
19410 /**
19411 * Returns a new list containing the first `n` elements of a given list, passing each value
19412 * to the supplied predicate function, and terminating when the predicate function returns
19413 * `false`. Excludes the element that caused the predicate function to fail. The predicate
19414 * function is passed one argument: *(value)*.
19415 *
19416 * Acts as a transducer if a transformer is given in list position.
19417 * @see R.transduce
19418 *
19419 * @func
19420 * @memberOf R
19421 * @category List
19422 * @sig (a -> Boolean) -> [a] -> [a]
19423 * @param {Function} fn The function called per iteration.
19424 * @param {Array} list The collection to iterate over.
19425 * @return {Array} A new array.
19426 * @example
19427 *
19428 * var isNotFour = function(x) {
19429 * return !(x === 4);
19430 * };
19431 *
19432 * R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3]
19433 */
19434 var takeWhile = _curry2(_dispatchable('takeWhile', _xtakeWhile, function takeWhile(fn, list) {
19435 var idx = -1, len = list.length;
19436 while (++idx < len && fn(list[idx])) {
19437 }
19438 return _slice(list, 0, idx);
19439 }));
19440
19441 /**
19442 * The lower case version of a string.
19443 *
19444 * @func
19445 * @memberOf R
19446 * @category String
19447 * @sig String -> String
19448 * @param {String} str The string to lower case.
19449 * @return {String} The lower case version of `str`.
19450 * @example
19451 *
19452 * R.toLower('XYZ'); //=> 'xyz'
19453 */
19454 var toLower = invoker(0, 'toLowerCase');
19455
19456 /**
19457 * The upper case version of a string.
19458 *
19459 * @func
19460 * @memberOf R
19461 * @category String
19462 * @sig String -> String
19463 * @param {String} str The string to upper case.
19464 * @return {String} The upper case version of `str`.
19465 * @example
19466 *
19467 * R.toUpper('abc'); //=> 'ABC'
19468 */
19469 var toUpper = invoker(0, 'toUpperCase');
19470
19471 /**
19472 * Initializes a transducer using supplied iterator function. Returns a single item by
19473 * iterating through the list, successively calling the transformed iterator function and
19474 * passing it an accumulator value and the current value from the array, and then passing
19475 * the result to the next call.
19476 *
19477 * The iterator function receives two values: *(acc, value)*. It will be wrapped as a
19478 * transformer to initialize the transducer. A transformer can be passed directly in place
19479 * of an iterator function.
19480 *
19481 * A transducer is a function that accepts a transformer and returns a transformer and can
19482 * be composed directly.
19483 *
19484 * A transformer is an an object that provides a 2-arity reducing iterator function, step,
19485 * 0-arity initial value function, init, and 1-arity result extraction function, result.
19486 * The step function is used as the iterator function in reduce. The result function is used
19487 * to convert the final accumulator into the return type and in most cases is R.identity.
19488 * The init function can be used to provide an initial accumulator, but is ignored by transduce.
19489 *
19490 * The iteration is performed with R.reduce after initializing the transducer.
19491 *
19492 * @func
19493 * @memberOf R
19494 * @category List
19495 * @sig (c -> c) -> (a,b -> a) -> a -> [b] -> a
19496 * @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
19497 * @param {Function} fn The iterator function. Receives two values, the accumulator and the
19498 * current element from the array. Wrapped as transformer, if necessary, and used to
19499 * initialize the transducer
19500 * @param {*} acc The initial accumulator value.
19501 * @param {Array} list The list to iterate over.
19502 * @see R.into
19503 * @return {*} The final, accumulated value.
19504 * @example
19505 *
19506 * var numbers = [1, 2, 3, 4];
19507 * var transducer = R.compose(R.map(R.add(1)), R.take(2));
19508 *
19509 * R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3]
19510 */
19511 var transduce = curryN(4, function (xf, fn, acc, list) {
19512 return _reduce(xf(typeof fn === 'function' ? _xwrap(fn) : fn), acc, list);
19513 });
19514
19515 /**
19516 * Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is
19517 * determined according to the value returned by applying the supplied predicate to two list elements.
19518 *
19519 * @func
19520 * @memberOf R
19521 * @category Relation
19522 * @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
19523 * @param {Function} pred A predicate used to test whether two items are equal.
19524 * @param {Array} list1 The first list.
19525 * @param {Array} list2 The second list.
19526 * @return {Array} The first and second lists concatenated, with
19527 * duplicates removed.
19528 * @see R.union
19529 * @example
19530 *
19531 * function cmp(x, y) { return x.a === y.a; }
19532 * var l1 = [{a: 1}, {a: 2}];
19533 * var l2 = [{a: 1}, {a: 4}];
19534 * R.unionWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}]
19535 */
19536 var unionWith = _curry3(function unionWith(pred, list1, list2) {
19537 return uniqWith(pred, _concat(list1, list2));
19538 });
19539
19540 /**
19541 * Returns a new list containing only one copy of each element in the original list.
19542 * Equality is strict here, meaning reference equality for objects and non-coercing equality
19543 * for primitives.
19544 *
19545 * @func
19546 * @memberOf R
19547 * @category List
19548 * @sig [a] -> [a]
19549 * @param {Array} list The array to consider.
19550 * @return {Array} The list of unique items.
19551 * @example
19552 *
19553 * R.uniq([1, 1, 2, 1]); //=> [1, 2]
19554 * R.uniq([{}, {}]); //=> [{}, {}]
19555 * R.uniq([1, '1']); //=> [1, '1']
19556 */
19557 var uniq = uniqWith(eq);
19558
19559 /**
19560 * Returns a new list by pulling every item at the first level of nesting out, and putting
19561 * them in a new array.
19562 *
19563 * @func
19564 * @memberOf R
19565 * @category List
19566 * @sig [a] -> [b]
19567 * @param {Array} list The array to consider.
19568 * @return {Array} The flattened list.
19569 * @example
19570 *
19571 * R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]]
19572 * R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6]
19573 */
19574 var unnest = _curry1(_makeFlat(false));
19575
19576 /**
19577 * Accepts a function `fn` and any number of transformer functions and returns a new
19578 * function. When the new function is invoked, it calls the function `fn` with parameters
19579 * consisting of the result of calling each supplied handler on successive arguments to the
19580 * new function.
19581 *
19582 * If more arguments are passed to the returned function than transformer functions, those
19583 * arguments are passed directly to `fn` as additional parameters. If you expect additional
19584 * arguments that don't need to be transformed, although you can ignore them, it's best to
19585 * pass an identity function so that the new function reports the correct arity.
19586 *
19587 * @func
19588 * @memberOf R
19589 * @category Function
19590 * @sig (x1 -> x2 -> ... -> z) -> ((a -> x1), (b -> x2), ...) -> (a -> b -> ... -> z)
19591 * @param {Function} fn The function to wrap.
19592 * @param {...Function} transformers A variable number of transformer functions
19593 * @return {Function} The wrapped function.
19594 * @example
19595 *
19596 * // Example 1:
19597 *
19598 * // Number -> [Person] -> [Person]
19599 * var byAge = R.useWith(R.filter, R.propEq('age'), R.identity);
19600 *
19601 * var kids = [
19602 * {name: 'Abbie', age: 6},
19603 * {name: 'Brian', age: 5},
19604 * {name: 'Chris', age: 6},
19605 * {name: 'David', age: 4},
19606 * {name: 'Ellie', age: 5}
19607 * ];
19608 *
19609 * byAge(5, kids); //=> [{name: 'Brian', age: 5}, {name: 'Ellie', age: 5}]
19610 *
19611 * // Example 2:
19612 *
19613 * var double = function(y) { return y * 2; };
19614 * var square = function(x) { return x * x; };
19615 * var add = function(a, b) { return a + b; };
19616 * // Adds any number of arguments together
19617 * var addAll = function() {
19618 * return R.reduce(add, 0, arguments);
19619 * };
19620 *
19621 * // Basic example
19622 * var addDoubleAndSquare = R.useWith(addAll, double, square);
19623 *
19624 * //≅ addAll(double(10), square(5));
19625 * addDoubleAndSquare(10, 5); //=> 45
19626 *
19627 * // Example of passing more arguments than transformers
19628 * //≅ addAll(double(10), square(5), 100);
19629 * addDoubleAndSquare(10, 5, 100); //=> 145
19630 *
19631 * // If there are extra _expected_ arguments that don't need to be transformed, although
19632 * // you can ignore them, it might be best to pass in the identity function so that the new
19633 * // function correctly reports arity.
19634 * var addDoubleAndSquareWithExtraParams = R.useWith(addAll, double, square, R.identity);
19635 * // addDoubleAndSquareWithExtraParams.length //=> 3
19636 * //≅ addAll(double(10), square(5), R.identity(100));
19637 * addDoubleAndSquare(10, 5, 100); //=> 145
19638 */
19639 /*, transformers */
19640 var useWith = curry(function useWith(fn) {
19641 var transformers = _slice(arguments, 1);
19642 var tlen = transformers.length;
19643 return curry(arity(tlen, function () {
19644 var args = [], idx = -1;
19645 while (++idx < tlen) {
19646 args[idx] = transformers[idx](arguments[idx]);
19647 }
19648 return fn.apply(this, args.concat(_slice(arguments, tlen)));
19649 }));
19650 });
19651
19652 /**
19653 * Returns a list of all the enumerable own properties of the supplied object.
19654 * Note that the order of the output array is not guaranteed across
19655 * different JS platforms.
19656 *
19657 * @func
19658 * @memberOf R
19659 * @category Object
19660 * @sig {k: v} -> [v]
19661 * @param {Object} obj The object to extract values from
19662 * @return {Array} An array of the values of the object's own properties.
19663 * @example
19664 *
19665 * R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]
19666 */
19667 var values = _curry1(function values(obj) {
19668 var props = keys(obj);
19669 var len = props.length;
19670 var vals = [];
19671 var idx = -1;
19672 while (++idx < len) {
19673 vals[idx] = obj[props[idx]];
19674 }
19675 return vals;
19676 });
19677
19678 /**
19679 * Takes a spec object and a test object; returns true if the test satisfies
19680 * the spec, false otherwise. An object satisfies the spec if, for each of the
19681 * spec's own properties, accessing that property of the object gives the same
19682 * value (in `R.eq` terms) as accessing that property of the spec.
19683 *
19684 * `whereEq` is a specialization of [`where`](#where).
19685 *
19686 * @func
19687 * @memberOf R
19688 * @category Object
19689 * @sig {String: *} -> {String: *} -> Boolean
19690 * @param {Object} spec
19691 * @param {Object} testObj
19692 * @return {Boolean}
19693 * @see R.where
19694 * @example
19695 *
19696 * // pred :: Object -> Boolean
19697 * var pred = R.where({a: 1, b: 2});
19698 *
19699 * pred({a: 1}); //=> false
19700 * pred({a: 1, b: 2}); //=> true
19701 * pred({a: 1, b: 2, c: 3}); //=> true
19702 * pred({a: 1, b: 1}); //=> false
19703 */
19704 var whereEq = _curry2(function whereEq(spec, testObj) {
19705 return where(mapObj(eq, spec), testObj);
19706 });
19707
19708 // The algorithm used to handle cyclic structures is
19709 // inspired by underscore's isEqual
19710 // RegExp equality algorithm: http://stackoverflow.com/a/10776635
19711 var _eqDeep = function _eqDeep(a, b, stackA, stackB) {
19712 var typeA = type(a);
19713 if (typeA !== type(b)) {
19714 return false;
19715 }
19716 if (eq(a, b)) {
19717 return true;
19718 }
19719 if (typeA == 'RegExp') {
19720 // RegExp equality algorithm: http://stackoverflow.com/a/10776635
19721 return a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode;
19722 }
19723 if (Object(a) === a) {
19724 if (typeA === 'Date' && a.getTime() != b.getTime()) {
19725 return false;
19726 }
19727 var keysA = keys(a);
19728 if (keysA.length !== keys(b).length) {
19729 return false;
19730 }
19731 var idx = stackA.length;
19732 while (--idx >= 0) {
19733 if (stackA[idx] === a) {
19734 return stackB[idx] === b;
19735 }
19736 }
19737 stackA[stackA.length] = a;
19738 stackB[stackB.length] = b;
19739 idx = keysA.length;
19740 while (--idx >= 0) {
19741 var key = keysA[idx];
19742 if (!_has(key, b) || !_eqDeep(b[key], a[key], stackA, stackB)) {
19743 return false;
19744 }
19745 }
19746 stackA.pop();
19747 stackB.pop();
19748 return true;
19749 }
19750 return false;
19751 };
19752
19753 /**
19754 * Assigns own enumerable properties of the other object to the destination
19755 * object preferring items in other.
19756 *
19757 * @private
19758 * @memberOf R
19759 * @category Object
19760 * @param {Object} destination The destination object.
19761 * @param {Object} other The other object to merge with destination.
19762 * @return {Object} The destination object.
19763 * @example
19764 *
19765 * _extend({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
19766 * //=> { 'name': 'fred', 'age': 40 }
19767 */
19768 var _extend = function _extend(destination, other) {
19769 var props = keys(other);
19770 var idx = -1, length = props.length;
19771 while (++idx < length) {
19772 destination[props[idx]] = other[props[idx]];
19773 }
19774 return destination;
19775 };
19776
19777 var _pluck = function _pluck(p, list) {
19778 return map(prop(p), list);
19779 };
19780
19781 /**
19782 * Create a predicate wrapper which will call a pick function (all/any) for each predicate
19783 *
19784 * @private
19785 * @see R.all
19786 * @see R.any
19787 */
19788 // Call function immediately if given arguments
19789 // Return a function which will call the predicates with the provided arguments
19790 var _predicateWrap = function _predicateWrap(predPicker) {
19791 return function (preds) {
19792 var predIterator = function () {
19793 var args = arguments;
19794 return predPicker(function (predicate) {
19795 return predicate.apply(null, args);
19796 }, preds);
19797 };
19798 return arguments.length > 1 ? // Call function immediately if given arguments
19799 predIterator.apply(null, _slice(arguments, 1)) : // Return a function which will call the predicates with the provided arguments
19800 arity(max(_pluck('length', preds)), predIterator);
19801 };
19802 };
19803
19804 // Function, RegExp, user-defined types
19805 var _toString = function _toString(x, seen) {
19806 var recur = function recur(y) {
19807 var xs = seen.concat([x]);
19808 return _indexOf(xs, y) >= 0 ? '<Circular>' : _toString(y, xs);
19809 };
19810 switch (Object.prototype.toString.call(x)) {
19811 case '[object Arguments]':
19812 return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))';
19813 case '[object Array]':
19814 return '[' + _map(recur, x).join(', ') + ']';
19815 case '[object Boolean]':
19816 return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString();
19817 case '[object Date]':
19818 return 'new Date(' + _quote(_toISOString(x)) + ')';
19819 case '[object Null]':
19820 return 'null';
19821 case '[object Number]':
19822 return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10);
19823 case '[object String]':
19824 return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x);
19825 case '[object Undefined]':
19826 return 'undefined';
19827 default:
19828 return typeof x.constructor === 'function' && x.constructor.name !== 'Object' && typeof x.toString === 'function' && x.toString() !== '[object Object]' ? x.toString() : // Function, RegExp, user-defined types
19829 '{' + _map(function (k) {
19830 return _quote(k) + ': ' + recur(x[k]);
19831 }, keys(x).sort()).join(', ') + '}';
19832 }
19833 };
19834
19835 /**
19836 * Given a list of predicates, returns a new predicate that will be true exactly when all of them are.
19837 *
19838 * @func
19839 * @memberOf R
19840 * @category Logic
19841 * @sig [(*... -> Boolean)] -> (*... -> Boolean)
19842 * @param {Array} list An array of predicate functions
19843 * @param {*} optional Any arguments to pass into the predicates
19844 * @return {Function} a function that applies its arguments to each of
19845 * the predicates, returning `true` if all are satisfied.
19846 * @example
19847 *
19848 * var gt10 = function(x) { return x > 10; };
19849 * var even = function(x) { return x % 2 === 0};
19850 * var f = R.allPass([gt10, even]);
19851 * f(11); //=> false
19852 * f(12); //=> true
19853 */
19854 var allPass = curry(_predicateWrap(_all));
19855
19856 /**
19857 * Given a list of predicates returns a new predicate that will be true exactly when any one of them is.
19858 *
19859 * @func
19860 * @memberOf R
19861 * @category Logic
19862 * @sig [(*... -> Boolean)] -> (*... -> Boolean)
19863 * @param {Array} list An array of predicate functions
19864 * @param {*} optional Any arguments to pass into the predicates
19865 * @return {Function} A function that applies its arguments to each of the predicates, returning
19866 * `true` if all are satisfied.
19867 * @example
19868 *
19869 * var gt10 = function(x) { return x > 10; };
19870 * var even = function(x) { return x % 2 === 0};
19871 * var f = R.anyPass([gt10, even]);
19872 * f(11); //=> true
19873 * f(8); //=> true
19874 * f(9); //=> false
19875 */
19876 var anyPass = curry(_predicateWrap(_any));
19877
19878 /**
19879 * ap applies a list of functions to a list of values.
19880 *
19881 * @func
19882 * @memberOf R
19883 * @category Function
19884 * @sig [f] -> [a] -> [f a]
19885 * @param {Array} fns An array of functions
19886 * @param {Array} vs An array of values
19887 * @return {Array} An array of results of applying each of `fns` to all of `vs` in turn.
19888 * @example
19889 *
19890 * R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]
19891 */
19892 var ap = _curry2(function ap(fns, vs) {
19893 return _hasMethod('ap', fns) ? fns.ap(vs) : _reduce(function (acc, fn) {
19894 return _concat(acc, map(fn, vs));
19895 }, [], fns);
19896 });
19897
19898 /**
19899 * Returns the result of calling its first argument with the remaining
19900 * arguments. This is occasionally useful as a converging function for
19901 * `R.converge`: the left branch can produce a function while the right
19902 * branch produces a value to be passed to that function as an argument.
19903 *
19904 * @func
19905 * @memberOf R
19906 * @category Function
19907 * @sig (*... -> a),*... -> a
19908 * @param {Function} fn The function to apply to the remaining arguments.
19909 * @param {...*} args Any number of positional arguments.
19910 * @return {*}
19911 * @example
19912 *
19913 * var indentN = R.pipe(R.times(R.always(' ')),
19914 * R.join(''),
19915 * R.replace(/^(?!$)/gm));
19916 *
19917 * var format = R.converge(R.call,
19918 * R.pipe(R.prop('indent'), indentN),
19919 * R.prop('value'));
19920 *
19921 * format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n'
19922 */
19923 var call = curry(function call(fn) {
19924 return fn.apply(this, _slice(arguments, 1));
19925 });
19926
19927 /**
19928 * `chain` maps a function over a list and concatenates the results.
19929 * This implementation is compatible with the
19930 * Fantasy-land Chain spec, and will work with types that implement that spec.
19931 * `chain` is also known as `flatMap` in some libraries
19932 *
19933 * @func
19934 * @memberOf R
19935 * @category List
19936 * @sig (a -> [b]) -> [a] -> [b]
19937 * @param {Function} fn
19938 * @param {Array} list
19939 * @return {Array}
19940 * @example
19941 *
19942 * var duplicate = function(n) {
19943 * return [n, n];
19944 * };
19945 * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
19946 */
19947 var chain = _curry2(_checkForMethod('chain', function chain(f, list) {
19948 return unnest(_map(f, list));
19949 }));
19950
19951 /**
19952 * Turns a list of Functors into a Functor of a list, applying
19953 * a mapping function to the elements of the list along the way.
19954 *
19955 * Note: `commuteMap` may be more useful to convert a list of non-Array Functors (e.g.
19956 * Maybe, Either, etc.) to Functor of a list.
19957 *
19958 * @func
19959 * @memberOf R
19960 * @category List
19961 * @see R.commute
19962 * @sig (a -> (b -> c)) -> (x -> [x]) -> [[*]...]
19963 * @param {Function} fn The transformation function
19964 * @param {Function} of A function that returns the data type to return
19965 * @param {Array} list An Array (or other Functor) of Arrays (or other Functors)
19966 * @return {Array}
19967 * @example
19968 *
19969 * var plus10map = R.map(function(x) { return x + 10; });
19970 * var as = [[1], [3, 4]];
19971 * R.commuteMap(R.map(function(x) { return x + 10; }), R.of, as); //=> [[11, 13], [11, 14]]
19972 *
19973 * var bs = [[1, 2], [3]];
19974 * R.commuteMap(plus10map, R.of, bs); //=> [[11, 13], [12, 13]]
19975 *
19976 * var cs = [[1, 2], [3, 4]];
19977 * R.commuteMap(plus10map, R.of, cs); //=> [[11, 13], [12, 13], [11, 14], [12, 14]]
19978 */
19979 var commuteMap = _curry3(function commuteMap(fn, of, list) {
19980 function consF(acc, ftor) {
19981 return ap(map(append, fn(ftor)), acc);
19982 }
19983 return _reduce(consF, of([]), list);
19984 });
19985
19986 /**
19987 * Wraps a constructor function inside a curried function that can be called with the same
19988 * arguments and returns the same type. The arity of the function returned is specified
19989 * to allow using variadic constructor functions.
19990 *
19991 * @func
19992 * @memberOf R
19993 * @category Function
19994 * @sig Number -> (* -> {*}) -> (* -> {*})
19995 * @param {Number} n The arity of the constructor function.
19996 * @param {Function} Fn The constructor function to wrap.
19997 * @return {Function} A wrapped, curried constructor function.
19998 * @example
19999 *
20000 * // Variadic constructor function
20001 * var Widget = function() {
20002 * this.children = Array.prototype.slice.call(arguments);
20003 * // ...
20004 * };
20005 * Widget.prototype = {
20006 * // ...
20007 * };
20008 * var allConfigs = {
20009 * // ...
20010 * };
20011 * R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets
20012 */
20013 var constructN = _curry2(function constructN(n, Fn) {
20014 if (n > 10) {
20015 throw new Error('Constructor with greater than ten arguments');
20016 }
20017 if (n === 0) {
20018 return function () {
20019 return new Fn();
20020 };
20021 }
20022 return curry(nAry(n, function ($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {
20023 switch (arguments.length) {
20024 case 1:
20025 return new Fn($0);
20026 case 2:
20027 return new Fn($0, $1);
20028 case 3:
20029 return new Fn($0, $1, $2);
20030 case 4:
20031 return new Fn($0, $1, $2, $3);
20032 case 5:
20033 return new Fn($0, $1, $2, $3, $4);
20034 case 6:
20035 return new Fn($0, $1, $2, $3, $4, $5);
20036 case 7:
20037 return new Fn($0, $1, $2, $3, $4, $5, $6);
20038 case 8:
20039 return new Fn($0, $1, $2, $3, $4, $5, $6, $7);
20040 case 9:
20041 return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8);
20042 case 10:
20043 return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9);
20044 }
20045 }));
20046 });
20047
20048 /**
20049 * Returns a new list without any consecutively repeating elements. Equality is
20050 * determined by applying the supplied predicate two consecutive elements.
20051 * The first element in a series of equal element is the one being preserved.
20052 *
20053 * Acts as a transducer if a transformer is given in list position.
20054 * @see R.transduce
20055 *
20056 * @func
20057 * @memberOf R
20058 * @category List
20059 * @sig (a, a -> Boolean) -> [a] -> [a]
20060 * @param {Function} pred A predicate used to test whether two items are equal.
20061 * @param {Array} list The array to consider.
20062 * @return {Array} `list` without repeating elements.
20063 * @example
20064 *
20065 * function lengthEq(x, y) { return Math.abs(x) === Math.abs(y); };
20066 * var l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3];
20067 * R.dropRepeatsWith(lengthEq, l); //=> [1, 3, 4, -5, 3]
20068 */
20069 var dropRepeatsWith = _curry2(_dispatchable('dropRepeatsWith', _xdropRepeatsWith, function dropRepeatsWith(pred, list) {
20070 var result = [];
20071 var idx = 0;
20072 var len = list.length;
20073 if (len !== 0) {
20074 result[0] = list[0];
20075 while (++idx < len) {
20076 if (!pred(last(result), list[idx])) {
20077 result[result.length] = list[idx];
20078 }
20079 }
20080 }
20081 return result;
20082 }));
20083
20084 /**
20085 * Performs a deep test on whether two items are equal.
20086 * Equality implies the two items are semmatically equivalent.
20087 * Cyclic structures are handled as expected
20088 *
20089 * @func
20090 * @memberOf R
20091 * @category Relation
20092 * @sig a -> b -> Boolean
20093 * @param {*} a
20094 * @param {*} b
20095 * @return {Boolean}
20096 * @example
20097 *
20098 * var o = {};
20099 * R.eqDeep(o, o); //=> true
20100 * R.eqDeep(o, {}); //=> true
20101 * R.eqDeep(1, 1); //=> true
20102 * R.eqDeep(1, '1'); //=> false
20103 *
20104 * var a = {}; a.v = a;
20105 * var b = {}; b.v = b;
20106 * R.eqDeep(a, b); //=> true
20107 */
20108 var eqDeep = _curry2(function eqDeep(a, b) {
20109 return _eqDeep(a, b, [], []);
20110 });
20111
20112 /**
20113 * Creates a new object by evolving a shallow copy of `object`, according to the
20114 * `transformation` functions. All non-primitive properties are copied by reference.
20115 *
20116 * @func
20117 * @memberOf R
20118 * @category Object
20119 * @sig {k: (v -> v)} -> {k: v} -> {k: v}
20120 * @param {Object} transformations The object specifying transformation functions to apply
20121 * to the object.
20122 * @param {Object} object The object to be transformed.
20123 * @return {Object} The transformed object.
20124 * @example
20125 *
20126 * R.evolve({ elapsed: R.add(1), remaining: R.add(-1) }, { name: 'Tomato', elapsed: 100, remaining: 1400 }); //=> { name: 'Tomato', elapsed: 101, remaining: 1399 }
20127 */
20128 var evolve = _curry2(function evolve(transformations, object) {
20129 return _extend(_extend({}, object), mapObjIndexed(function (fn, key) {
20130 return fn(object[key]);
20131 }, transformations));
20132 });
20133
20134 /**
20135 * Returns a list of function names of object's own functions
20136 *
20137 * @func
20138 * @memberOf R
20139 * @category Object
20140 * @sig {*} -> [String]
20141 * @param {Object} obj The objects with functions in it
20142 * @return {Array} A list of the object's own properties that map to functions.
20143 * @example
20144 *
20145 * R.functions(R); // returns list of ramda's own function names
20146 *
20147 * var F = function() { this.x = function(){}; this.y = 1; }
20148 * F.prototype.z = function() {};
20149 * F.prototype.a = 100;
20150 * R.functions(new F()); //=> ["x"]
20151 */
20152 var functions = _curry1(_functionsWith(keys));
20153
20154 /**
20155 * Returns all but the last element of a list.
20156 *
20157 * @func
20158 * @memberOf R
20159 * @category List
20160 * @sig [a] -> [a]
20161 * @param {Array} list The array to consider.
20162 * @return {Array} A new array containing all but the last element of the input list, or an
20163 * empty list if the input list is empty.
20164 * @example
20165 *
20166 * R.init(['fi', 'fo', 'fum']); //=> ['fi', 'fo']
20167 */
20168 var init = slice(0, -1);
20169
20170 /**
20171 * Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists.
20172 *
20173 * @func
20174 * @memberOf R
20175 * @category Relation
20176 * @sig [a] -> [a] -> [a]
20177 * @param {Array} list1 The first list.
20178 * @param {Array} list2 The second list.
20179 * @see R.intersectionWith
20180 * @return {Array} The list of elements found in both `list1` and `list2`.
20181 * @example
20182 *
20183 * R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]
20184 */
20185 var intersection = _curry2(function intersection(list1, list2) {
20186 return uniq(_filter(flip(_contains)(list1), list2));
20187 });
20188
20189 /**
20190 * Same as R.invertObj, however this accounts for objects
20191 * with duplicate values by putting the values into an
20192 * array.
20193 *
20194 * @func
20195 * @memberOf R
20196 * @category Object
20197 * @sig {s: x} -> {x: [ s, ... ]}
20198 * @param {Object} obj The object or array to invert
20199 * @return {Object} out A new object with keys
20200 * in an array.
20201 * @example
20202 *
20203 * var raceResultsByFirstName = {
20204 * first: 'alice',
20205 * second: 'jake',
20206 * third: 'alice',
20207 * };
20208 * R.invert(raceResultsByFirstName);
20209 * //=> { 'alice': ['first', 'third'], 'jake':['second'] }
20210 */
20211 var invert = _curry1(function invert(obj) {
20212 var props = keys(obj);
20213 var len = props.length;
20214 var idx = -1;
20215 var out = {};
20216 while (++idx < len) {
20217 var key = props[idx];
20218 var val = obj[key];
20219 var list = _has(val, out) ? out[val] : out[val] = [];
20220 list[list.length] = key;
20221 }
20222 return out;
20223 });
20224
20225 /**
20226 * Returns a new object with the keys of the given object
20227 * as values, and the values of the given object as keys.
20228 *
20229 * @func
20230 * @memberOf R
20231 * @category Object
20232 * @sig {s: x} -> {x: s}
20233 * @param {Object} obj The object or array to invert
20234 * @return {Object} out A new object
20235 * @example
20236 *
20237 * var raceResults = {
20238 * first: 'alice',
20239 * second: 'jake'
20240 * };
20241 * R.invertObj(raceResults);
20242 * //=> { 'alice': 'first', 'jake':'second' }
20243 *
20244 * // Alternatively:
20245 * var raceResults = ['alice', 'jake'];
20246 * R.invertObj(raceResults);
20247 * //=> { 'alice': '0', 'jake':'1' }
20248 */
20249 var invertObj = _curry1(function invertObj(obj) {
20250 var props = keys(obj);
20251 var len = props.length;
20252 var idx = -1;
20253 var out = {};
20254 while (++idx < len) {
20255 var key = props[idx];
20256 out[obj[key]] = key;
20257 }
20258 return out;
20259 });
20260
20261 /**
20262 * "lifts" a function to be the specified arity, so that it may "map over" that many
20263 * lists (or other Functors).
20264 *
20265 * @func
20266 * @memberOf R
20267 * @see R.lift
20268 * @category Function
20269 * @sig Number -> (*... -> *) -> ([*]... -> [*])
20270 * @param {Function} fn The function to lift into higher context
20271 * @return {Function} The function `fn` applicable to mappable objects.
20272 * @example
20273 *
20274 * var madd3 = R.liftN(3, R.curryN(3, function() {
20275 * return R.reduce(R.add, 0, arguments);
20276 * }));
20277 * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
20278 */
20279 var liftN = _curry2(function liftN(arity, fn) {
20280 var lifted = curryN(arity, fn);
20281 return curryN(arity, function () {
20282 return _reduce(ap, map(lifted, arguments[0]), _slice(arguments, 1));
20283 });
20284 });
20285
20286 /**
20287 * Returns the mean of the given list of numbers.
20288 *
20289 * @func
20290 * @memberOf R
20291 * @category Math
20292 * @sig [Number] -> Number
20293 * @param {Array} list
20294 * @return {Number}
20295 * @example
20296 *
20297 * R.mean([2, 7, 9]); //=> 6
20298 * R.mean([]); //=> NaN
20299 */
20300 var mean = _curry1(function mean(list) {
20301 return sum(list) / list.length;
20302 });
20303
20304 /**
20305 * Returns the median of the given list of numbers.
20306 *
20307 * @func
20308 * @memberOf R
20309 * @category Math
20310 * @sig [Number] -> Number
20311 * @param {Array} list
20312 * @return {Number}
20313 * @example
20314 *
20315 * R.median([2, 9, 7]); //=> 7
20316 * R.median([7, 2, 10, 9]); //=> 8
20317 * R.median([]); //=> NaN
20318 */
20319 var median = _curry1(function median(list) {
20320 var len = list.length;
20321 if (len === 0) {
20322 return NaN;
20323 }
20324 var width = 2 - len % 2;
20325 var idx = (len - width) / 2;
20326 return mean(_slice(list).sort(function (a, b) {
20327 return a < b ? -1 : a > b ? 1 : 0;
20328 }).slice(idx, idx + width));
20329 });
20330
20331 /**
20332 * Create a new object with the own properties of a
20333 * merged with the own properties of object b.
20334 * This function will *not* mutate passed-in objects.
20335 *
20336 * @func
20337 * @memberOf R
20338 * @category Object
20339 * @sig {k: v} -> {k: v} -> {k: v}
20340 * @param {Object} a source object
20341 * @param {Object} b object with higher precedence in output
20342 * @return {Object} The destination object.
20343 * @example
20344 *
20345 * R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
20346 * //=> { 'name': 'fred', 'age': 40 }
20347 *
20348 * var resetToDefault = R.merge(R.__, {x: 0});
20349 * resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2}
20350 */
20351 var merge = _curry2(function merge(a, b) {
20352 return _extend(_extend({}, a), b);
20353 });
20354
20355 /**
20356 * Merges a list of objects together into one object.
20357 *
20358 * @func
20359 * @memberOf R
20360 * @category List
20361 * @sig [{k: v}] -> {k: v}
20362 * @param {Array} list An array of objects
20363 * @return {Object} A merged object.
20364 * @see reduce
20365 * @example
20366 *
20367 * R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3}
20368 * R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2}
20369 */
20370 var mergeAll = _curry1(function mergeAll(list) {
20371 return reduce(merge, {}, list);
20372 });
20373
20374 /**
20375 * Returns a new list by plucking the same named property off all objects in the list supplied.
20376 *
20377 * @func
20378 * @memberOf R
20379 * @category List
20380 * @sig String -> {*} -> [*]
20381 * @param {Number|String} key The key name to pluck off of each object.
20382 * @param {Array} list The array to consider.
20383 * @return {Array} The list of values for the given key.
20384 * @example
20385 *
20386 * R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2]
20387 * R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3]
20388 */
20389 var pluck = _curry2(_pluck);
20390
20391 /**
20392 * Multiplies together all the elements of a list.
20393 *
20394 * @func
20395 * @memberOf R
20396 * @category Math
20397 * @sig [Number] -> Number
20398 * @param {Array} list An array of numbers
20399 * @return {Number} The product of all the numbers in the list.
20400 * @see reduce
20401 * @example
20402 *
20403 * R.product([2,4,6,8,100,1]); //=> 38400
20404 */
20405 var product = reduce(_multiply, 1);
20406
20407 /**
20408 * Reasonable analog to SQL `select` statement.
20409 *
20410 * @func
20411 * @memberOf R
20412 * @category Object
20413 * @category Relation
20414 * @sig [k] -> [{k: v}] -> [{k: v}]
20415 * @param {Array} props The property names to project
20416 * @param {Array} objs The objects to query
20417 * @return {Array} An array of objects with just the `props` properties.
20418 * @example
20419 *
20420 * var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2};
20421 * var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7};
20422 * var kids = [abby, fred];
20423 * R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
20424 */
20425 // passing `identity` gives correct arity
20426 var project = useWith(_map, pickAll, identity);
20427
20428 /**
20429 * Returns the string representation of the given value. `eval`'ing the output
20430 * should result in a value equivalent to the input value. Many of the built-in
20431 * `toString` methods do not satisfy this requirement.
20432 *
20433 * If the given value is an `[object Object]` with a `toString` method other
20434 * than `Object.prototype.toString`, this method is invoked with no arguments
20435 * to produce the return value. This means user-defined constructor functions
20436 * can provide a suitable `toString` method. For example:
20437 *
20438 * function Point(x, y) {
20439 * this.x = x;
20440 * this.y = y;
20441 * }
20442 *
20443 * Point.prototype.toString = function() {
20444 * return 'new Point(' + this.x + ', ' + this.y + ')';
20445 * };
20446 *
20447 * R.toString(new Point(1, 2)); //=> 'new Point(1, 2)'
20448 *
20449 * @func
20450 * @memberOf R
20451 * @category String
20452 * @sig * -> String
20453 * @param {*} val
20454 * @return {String}
20455 * @example
20456 *
20457 * R.toString(42); //=> '42'
20458 * R.toString('abc'); //=> '"abc"'
20459 * R.toString([1, 2, 3]); //=> '[1, 2, 3]'
20460 * R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}'
20461 * R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")'
20462 */
20463 var toString = _curry1(function toString(val) {
20464 return _toString(val, []);
20465 });
20466
20467 /**
20468 * Combines two lists into a set (i.e. no duplicates) composed of the
20469 * elements of each list.
20470 *
20471 * @func
20472 * @memberOf R
20473 * @category Relation
20474 * @sig [a] -> [a] -> [a]
20475 * @param {Array} as The first list.
20476 * @param {Array} bs The second list.
20477 * @return {Array} The first and second lists concatenated, with
20478 * duplicates removed.
20479 * @example
20480 *
20481 * R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4]
20482 */
20483 var union = _curry2(compose(uniq, _concat));
20484
20485 var _stepCat = function () {
20486 var _stepCatArray = {
20487 '@@transducer/init': Array,
20488 '@@transducer/step': function (xs, x) {
20489 return _concat(xs, [x]);
20490 },
20491 '@@transducer/result': _identity
20492 };
20493 var _stepCatString = {
20494 '@@transducer/init': String,
20495 '@@transducer/step': _add,
20496 '@@transducer/result': _identity
20497 };
20498 var _stepCatObject = {
20499 '@@transducer/init': Object,
20500 '@@transducer/step': function (result, input) {
20501 return merge(result, isArrayLike(input) ? _createMapEntry(input[0], input[1]) : input);
20502 },
20503 '@@transducer/result': _identity
20504 };
20505 return function _stepCat(obj) {
20506 if (_isTransformer(obj)) {
20507 return obj;
20508 }
20509 if (isArrayLike(obj)) {
20510 return _stepCatArray;
20511 }
20512 if (typeof obj === 'string') {
20513 return _stepCatString;
20514 }
20515 if (typeof obj === 'object') {
20516 return _stepCatObject;
20517 }
20518 throw new Error('Cannot create transformer for ' + obj);
20519 };
20520 }();
20521
20522 /**
20523 * Turns a list of Functors into a Functor of a list.
20524 *
20525 * Note: `commute` may be more useful to convert a list of non-Array Functors (e.g.
20526 * Maybe, Either, etc.) to Functor of a list.
20527 *
20528 * @func
20529 * @memberOf R
20530 * @category List
20531 * @see R.commuteMap
20532 * @sig (x -> [x]) -> [[*]...]
20533 * @param {Function} of A function that returns the data type to return
20534 * @param {Array} list An Array (or other Functor) of Arrays (or other Functors)
20535 * @return {Array}
20536 * @example
20537 *
20538 * var as = [[1], [3, 4]];
20539 * R.commute(R.of, as); //=> [[1, 3], [1, 4]]
20540 *
20541 * var bs = [[1, 2], [3]];
20542 * R.commute(R.of, bs); //=> [[1, 3], [2, 3]]
20543 *
20544 * var cs = [[1, 2], [3, 4]];
20545 * R.commute(R.of, cs); //=> [[1, 3], [2, 3], [1, 4], [2, 4]]
20546 */
20547 var commute = commuteMap(map(identity));
20548
20549 /**
20550 * Wraps a constructor function inside a curried function that can be called with the same
20551 * arguments and returns the same type.
20552 *
20553 * @func
20554 * @memberOf R
20555 * @category Function
20556 * @sig (* -> {*}) -> (* -> {*})
20557 * @param {Function} Fn The constructor function to wrap.
20558 * @return {Function} A wrapped, curried constructor function.
20559 * @example
20560 *
20561 * // Constructor function
20562 * var Widget = function(config) {
20563 * // ...
20564 * };
20565 * Widget.prototype = {
20566 * // ...
20567 * };
20568 * var allConfigs = {
20569 * // ...
20570 * };
20571 * R.map(R.construct(Widget), allConfigs); // a list of Widgets
20572 */
20573 var construct = _curry1(function construct(Fn) {
20574 return constructN(Fn.length, Fn);
20575 });
20576
20577 /**
20578 * Accepts at least three functions and returns a new function. When invoked, this new
20579 * function will invoke the first function, `after`, passing as its arguments the
20580 * results of invoking the subsequent functions with whatever arguments are passed to
20581 * the new function.
20582 *
20583 * @func
20584 * @memberOf R
20585 * @category Function
20586 * @sig (x1 -> x2 -> ... -> z) -> ((a -> b -> ... -> x1), (a -> b -> ... -> x2), ...) -> (a -> b -> ... -> z)
20587 * @param {Function} after A function. `after` will be invoked with the return values of
20588 * `fn1` and `fn2` as its arguments.
20589 * @param {...Function} functions A variable number of functions.
20590 * @return {Function} A new function.
20591 * @example
20592 *
20593 * var add = function(a, b) { return a + b; };
20594 * var multiply = function(a, b) { return a * b; };
20595 * var subtract = function(a, b) { return a - b; };
20596 *
20597 * //≅ multiply( add(1, 2), subtract(1, 2) );
20598 * R.converge(multiply, add, subtract)(1, 2); //=> -3
20599 *
20600 * var add3 = function(a, b, c) { return a + b + c; };
20601 * R.converge(add3, multiply, add, subtract)(1, 2); //=> 4
20602 */
20603 var converge = curryN(3, function (after) {
20604 var fns = _slice(arguments, 1);
20605 return curryN(max(pluck('length', fns)), function () {
20606 var args = arguments;
20607 var context = this;
20608 return after.apply(context, _map(function (fn) {
20609 return fn.apply(context, args);
20610 }, fns));
20611 });
20612 });
20613
20614 /**
20615 * Returns a new list without any consecutively repeating elements.
20616 *
20617 * Acts as a transducer if a transformer is given in list position.
20618 * @see R.transduce
20619 *
20620 * @func
20621 * @memberOf R
20622 * @category List
20623 * @sig [a] -> [a]
20624 * @param {Array} list The array to consider.
20625 * @return {Array} `list` without repeating elements.
20626 * @example
20627 *
20628 * R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2]
20629 */
20630 var dropRepeats = _curry1(_dispatchable('dropRepeats', _xdropRepeatsWith(_eq), dropRepeatsWith(_eq)));
20631
20632 /**
20633 * Transforms the items of the list with the transducer and appends the transformed items to
20634 * the accumulator using an appropriate iterator function based on the accumulator type.
20635 *
20636 * The accumulator can be an array, string, object or a transformer. Iterated items will
20637 * be appended to arrays and concatenated to strings. Objects will be merged directly or 2-item
20638 * arrays will be merged as key, value pairs.
20639 *
20640 * The accumulator can also be a transformer object that provides a 2-arity reducing iterator
20641 * function, step, 0-arity initial value function, init, and 1-arity result extraction function
20642 * result. The step function is used as the iterator function in reduce. The result function is
20643 * used to convert the final accumulator into the return type and in most cases is R.identity.
20644 * The init function is used to provide the initial accumulator.
20645 *
20646 * The iteration is performed with R.reduce after initializing the transducer.
20647 *
20648 * @func
20649 * @memberOf R
20650 * @category List
20651 * @sig a -> (b -> b) -> [c] -> a
20652 * @param {*} acc The initial accumulator value.
20653 * @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
20654 * @param {Array} list The list to iterate over.
20655 * @return {*} The final, accumulated value.
20656 * @example
20657 *
20658 * var numbers = [1, 2, 3, 4];
20659 * var transducer = R.compose(R.map(R.add(1)), R.take(2));
20660 *
20661 * R.into([], transducer, numbers); //=> [2, 3]
20662 *
20663 * var intoArray = R.into([]);
20664 * intoArray(transducer, numbers); //=> [2, 3]
20665 */
20666 var into = _curry3(function into(acc, xf, list) {
20667 return _isTransformer(acc) ? _reduce(xf(acc), acc['@@transducer/init'](), list) : _reduce(xf(_stepCat(acc)), acc, list);
20668 });
20669
20670 /**
20671 * "lifts" a function of arity > 1 so that it may "map over" an Array or
20672 * other Functor.
20673 *
20674 * @func
20675 * @memberOf R
20676 * @see R.liftN
20677 * @category Function
20678 * @sig (*... -> *) -> ([*]... -> [*])
20679 * @param {Function} fn The function to lift into higher context
20680 * @return {Function} The function `fn` applicable to mappable objects.
20681 * @example
20682 *
20683 * var madd3 = R.lift(R.curry(function(a, b, c) {
20684 * return a + b + c;
20685 * }));
20686 * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
20687 *
20688 * var madd5 = R.lift(R.curry(function(a, b, c, d, e) {
20689 * return a + b + c + d + e;
20690 * }));
20691 * madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24]
20692 */
20693 var lift = _curry1(function lift(fn) {
20694 return liftN(fn.length, fn);
20695 });
20696
20697 /**
20698 * Creates a new function that, when invoked, caches the result of calling `fn` for a given
20699 * argument set and returns the result. Subsequent calls to the memoized `fn` with the same
20700 * argument set will not result in an additional call to `fn`; instead, the cached result
20701 * for that set of arguments will be returned.
20702 *
20703 * @func
20704 * @memberOf R
20705 * @category Function
20706 * @sig (*... -> a) -> (*... -> a)
20707 * @param {Function} fn The function to memoize.
20708 * @return {Function} Memoized version of `fn`.
20709 * @example
20710 *
20711 * var count = 0;
20712 * var factorial = R.memoize(function(n) {
20713 * count += 1;
20714 * return R.product(R.range(1, n + 1));
20715 * });
20716 * factorial(5); //=> 120
20717 * factorial(5); //=> 120
20718 * factorial(5); //=> 120
20719 * count; //=> 1
20720 */
20721 var memoize = _curry1(function memoize(fn) {
20722 var cache = {};
20723 return function () {
20724 var key = toString(arguments);
20725 if (!_has(key, cache)) {
20726 cache[key] = fn.apply(this, arguments);
20727 }
20728 return cache[key];
20729 };
20730 });
20731
20732 var R = {
20733 F: F,
20734 T: T,
20735 __: __,
20736 add: add,
20737 adjust: adjust,
20738 all: all,
20739 allPass: allPass,
20740 always: always,
20741 and: and,
20742 any: any,
20743 anyPass: anyPass,
20744 ap: ap,
20745 aperture: aperture,
20746 append: append,
20747 apply: apply,
20748 arity: arity,
20749 assoc: assoc,
20750 assocPath: assocPath,
20751 binary: binary,
20752 bind: bind,
20753 both: both,
20754 call: call,
20755 chain: chain,
20756 clone: clone,
20757 commute: commute,
20758 commuteMap: commuteMap,
20759 comparator: comparator,
20760 complement: complement,
20761 compose: compose,
20762 composeL: composeL,
20763 composeP: composeP,
20764 concat: concat,
20765 cond: cond,
20766 construct: construct,
20767 constructN: constructN,
20768 contains: contains,
20769 containsWith: containsWith,
20770 converge: converge,
20771 countBy: countBy,
20772 createMapEntry: createMapEntry,
20773 curry: curry,
20774 curryN: curryN,
20775 dec: dec,
20776 defaultTo: defaultTo,
20777 difference: difference,
20778 differenceWith: differenceWith,
20779 dissoc: dissoc,
20780 dissocPath: dissocPath,
20781 divide: divide,
20782 drop: drop,
20783 dropRepeats: dropRepeats,
20784 dropRepeatsWith: dropRepeatsWith,
20785 dropWhile: dropWhile,
20786 either: either,
20787 empty: empty,
20788 eq: eq,
20789 eqDeep: eqDeep,
20790 eqProps: eqProps,
20791 evolve: evolve,
20792 filter: filter,
20793 filterIndexed: filterIndexed,
20794 find: find,
20795 findIndex: findIndex,
20796 findLast: findLast,
20797 findLastIndex: findLastIndex,
20798 flatten: flatten,
20799 flip: flip,
20800 forEach: forEach,
20801 forEachIndexed: forEachIndexed,
20802 fromPairs: fromPairs,
20803 functions: functions,
20804 functionsIn: functionsIn,
20805 groupBy: groupBy,
20806 gt: gt,
20807 gte: gte,
20808 has: has,
20809 hasIn: hasIn,
20810 head: head,
20811 identity: identity,
20812 ifElse: ifElse,
20813 inc: inc,
20814 indexOf: indexOf,
20815 init: init,
20816 insert: insert,
20817 insertAll: insertAll,
20818 intersection: intersection,
20819 intersectionWith: intersectionWith,
20820 intersperse: intersperse,
20821 into: into,
20822 invert: invert,
20823 invertObj: invertObj,
20824 invoke: invoke,
20825 invoker: invoker,
20826 is: is,
20827 isArrayLike: isArrayLike,
20828 isEmpty: isEmpty,
20829 isNaN: isNaN,
20830 isNil: isNil,
20831 isSet: isSet,
20832 join: join,
20833 keys: keys,
20834 keysIn: keysIn,
20835 last: last,
20836 lastIndexOf: lastIndexOf,
20837 length: length,
20838 lens: lens,
20839 lensIndex: lensIndex,
20840 lensOn: lensOn,
20841 lensProp: lensProp,
20842 lift: lift,
20843 liftN: liftN,
20844 lt: lt,
20845 lte: lte,
20846 map: map,
20847 mapAccum: mapAccum,
20848 mapAccumRight: mapAccumRight,
20849 mapIndexed: mapIndexed,
20850 mapObj: mapObj,
20851 mapObjIndexed: mapObjIndexed,
20852 match: match,
20853 mathMod: mathMod,
20854 max: max,
20855 maxBy: maxBy,
20856 mean: mean,
20857 median: median,
20858 memoize: memoize,
20859 merge: merge,
20860 mergeAll: mergeAll,
20861 min: min,
20862 minBy: minBy,
20863 modulo: modulo,
20864 multiply: multiply,
20865 nAry: nAry,
20866 negate: negate,
20867 none: none,
20868 not: not,
20869 nth: nth,
20870 nthArg: nthArg,
20871 nthChar: nthChar,
20872 nthCharCode: nthCharCode,
20873 of: of,
20874 omit: omit,
20875 once: once,
20876 or: or,
20877 partial: partial,
20878 partialRight: partialRight,
20879 partition: partition,
20880 path: path,
20881 pathEq: pathEq,
20882 pick: pick,
20883 pickAll: pickAll,
20884 pickBy: pickBy,
20885 pipe: pipe,
20886 pipeL: pipeL,
20887 pipeP: pipeP,
20888 pluck: pluck,
20889 prepend: prepend,
20890 product: product,
20891 project: project,
20892 prop: prop,
20893 propEq: propEq,
20894 propOr: propOr,
20895 props: props,
20896 range: range,
20897 reduce: reduce,
20898 reduceIndexed: reduceIndexed,
20899 reduceRight: reduceRight,
20900 reduceRightIndexed: reduceRightIndexed,
20901 reject: reject,
20902 rejectIndexed: rejectIndexed,
20903 remove: remove,
20904 repeat: repeat,
20905 replace: replace,
20906 reverse: reverse,
20907 scan: scan,
20908 slice: slice,
20909 sort: sort,
20910 sortBy: sortBy,
20911 split: split,
20912 strIndexOf: strIndexOf,
20913 strLastIndexOf: strLastIndexOf,
20914 substring: substring,
20915 substringFrom: substringFrom,
20916 substringTo: substringTo,
20917 subtract: subtract,
20918 sum: sum,
20919 tail: tail,
20920 take: take,
20921 takeWhile: takeWhile,
20922 tap: tap,
20923 test: test,
20924 times: times,
20925 toLower: toLower,
20926 toPairs: toPairs,
20927 toPairsIn: toPairsIn,
20928 toString: toString,
20929 toUpper: toUpper,
20930 transduce: transduce,
20931 trim: trim,
20932 type: type,
20933 unapply: unapply,
20934 unary: unary,
20935 uncurryN: uncurryN,
20936 unfold: unfold,
20937 union: union,
20938 unionWith: unionWith,
20939 uniq: uniq,
20940 uniqWith: uniqWith,
20941 unnest: unnest,
20942 update: update,
20943 useWith: useWith,
20944 values: values,
20945 valuesIn: valuesIn,
20946 where: where,
20947 whereEq: whereEq,
20948 wrap: wrap,
20949 xprod: xprod,
20950 zip: zip,
20951 zipObj: zipObj,
20952 zipWith: zipWith
20953 };
20954
20955 /* TEST_ENTRY_POINT */
20956
20957 if (true) {
20958 module.exports = R;
20959 } else if (typeof define === 'function' && define.amd) {
20960 define(function() { return R; });
20961 } else {
20962 this.R = R;
20963 }
20964
20965 }.call(this));
20966
20967
20968/***/ },
20969/* 12 */
20970/***/ function(module, exports, __webpack_require__) {
20971
20972 module.exports = function(module) {
20973 if(!module.webpackPolyfill) {
20974 module.deprecate = function() {};
20975 module.paths = [];
20976 // module.parent = undefined by default
20977 module.children = [];
20978 module.webpackPolyfill = 1;
20979 }
20980 return module;
20981 }
20982
20983
20984/***/ },
20985/* 13 */
20986/***/ function(module, exports, __webpack_require__) {
20987
20988 var __WEBPACK_AMD_DEFINE_RESULT__;/**
20989 * This module exports functions for checking types
20990 * and throwing exceptions.
20991 */
20992
20993 /*globals define, module */
20994
20995 (function (globals) {
20996 'use strict';
20997
20998 var messages, predicates, functions, verify, maybe, not;
20999
21000 predicates = {
21001 like: like,
21002 instance: instance,
21003 emptyObject: emptyObject,
21004 nulled: nulled,
21005 defined: defined,
21006 object: object,
21007 length: length,
21008 array: array,
21009 date: date,
21010 fn: fn,
21011 webUrl: webUrl,
21012 gitUrl: gitUrl,
21013 email: email,
21014 unemptyString: unemptyString,
21015 string: string,
21016 evenNumber: evenNumber,
21017 oddNumber: oddNumber,
21018 positiveNumber: positiveNumber,
21019 negativeNumber: negativeNumber,
21020 intNumber : intNumber,
21021 floatNumber : floatNumber,
21022 number: number,
21023 bool: bool
21024 };
21025
21026 messages = {
21027 like: 'Invalid type',
21028 instance: 'Invalid type',
21029 emptyObject: 'Invalid object',
21030 nulled: 'Not null',
21031 defined: 'Not defined',
21032 object: 'Invalid object',
21033 length: 'Invalid length',
21034 array: 'Invalid array',
21035 date: 'Invalid date',
21036 fn: 'Invalid function',
21037 webUrl: 'Invalid URL',
21038 gitUrl: 'Invalid git URL',
21039 email: 'Invalid email',
21040 unemptyString: 'Invalid string',
21041 string: 'Invalid string',
21042 evenNumber: 'Invalid number',
21043 oddNumber: 'Invalid number',
21044 positiveNumber: 'Invalid number',
21045 negativeNumber: 'Invalid number',
21046 intNumber: 'Invalid number',
21047 floatNumber: 'Invalid number',
21048 number: 'Invalid number',
21049 bool: 'Invalid boolean'
21050 };
21051
21052 functions = {
21053 map: map,
21054 every: every,
21055 any: any
21056 };
21057
21058 functions = mixin(functions, predicates);
21059 verify = createModifiedPredicates(verifyModifier);
21060 maybe = createModifiedPredicates(maybeModifier);
21061 not = createModifiedPredicates(notModifier);
21062 verify.maybe = createModifiedFunctions(verifyModifier, maybe);
21063 verify.not = createModifiedFunctions(verifyModifier, not);
21064
21065 exportFunctions(mixin(functions, {
21066 verify: verify,
21067 maybe: maybe,
21068 not: not
21069 }));
21070
21071 /**
21072 * Public function `like`.
21073 *
21074 * Tests whether an object 'quacks like a duck'.
21075 * Returns `true` if the first argument has all of
21076 * the properties of the second, archetypal argument
21077 * (the 'duck'). Returns `false` otherwise. If either
21078 * argument is not an object, an exception is thrown.
21079 *
21080 * @param thing {object} The object to test.
21081 * @param duck {object} The archetypal object, or
21082 * 'duck', that the test is
21083 * against.
21084 */
21085 function like (thing, duck) {
21086 var name;
21087
21088 verify.object(thing);
21089 verify.object(duck);
21090
21091 for (name in duck) {
21092 if (duck.hasOwnProperty(name)) {
21093 if (thing.hasOwnProperty(name) === false || typeof thing[name] !== typeof duck[name]) {
21094 return false;
21095 }
21096
21097 if (object(thing[name]) && like(thing[name], duck[name]) === false) {
21098 return false;
21099 }
21100 }
21101 }
21102
21103 return true;
21104 }
21105
21106 /**
21107 * Public function `instance`.
21108 *
21109 * Returns `true` if an object is an instance of a prototype,
21110 * `false` otherwise.
21111 *
21112 * @param thing {object} The object to test.
21113 * @param prototype {function} The prototype that the
21114 * test is against.
21115 */
21116 function instance (thing, prototype) {
21117 if (!defined(thing) || nulled(thing)) {
21118 return false;
21119 }
21120
21121 if (fn(prototype) && thing instanceof prototype) {
21122 return true;
21123 }
21124
21125 return false;
21126 }
21127
21128 /**
21129 * Public function `emptyObject`.
21130 *
21131 * Returns `true` if something is an empty, non-null,
21132 * non-array object, `false` otherwise.
21133 *
21134 * @param thing The thing to test.
21135 */
21136 function emptyObject (thing) {
21137 var property;
21138
21139 if (object(thing)) {
21140 for (property in thing) {
21141 if (thing.hasOwnProperty(property)) {
21142 return false;
21143 }
21144 }
21145
21146 return true;
21147 }
21148
21149 return false;
21150 }
21151
21152 /**
21153 * Public function `nulled`.
21154 *
21155 * Returns `true` if something is null,
21156 * `false` otherwise.
21157 *
21158 * @param thing The thing to test.
21159 */
21160 function nulled (thing) {
21161 return thing === null;
21162 }
21163
21164 /**
21165 * Public function `defined`.
21166 *
21167 * Returns `true` if something is not undefined,
21168 * `false` otherwise.
21169 *
21170 * @param thing The thing to test.
21171 */
21172 function defined (thing) {
21173 return thing !== void 0;
21174 }
21175
21176 /**
21177 * Public function `object`.
21178 *
21179 * Returns `true` if something is a non-null, non-array,
21180 * non-date object, `false` otherwise.
21181 *
21182 * @param thing The thing to test.
21183 */
21184 function object (thing) {
21185 return typeof thing === 'object' && !nulled(thing) && !array(thing) && !date(thing);
21186 }
21187
21188 /**
21189 * Public function `length`.
21190 *
21191 * Returns `true` if something is has a length property
21192 * that equals `value`, `false` otherwise.
21193 *
21194 * @param thing The thing to test.
21195 * @param value The required length to test against.
21196 */
21197 function length (thing, value) {
21198 return thing && thing.length === value;
21199 }
21200
21201 /**
21202 * Public function `array`.
21203 *
21204 * Returns `true` something is an array, `false` otherwise.
21205 *
21206 * @param thing The thing to test.
21207 */
21208 function array (thing) {
21209 if (Array.isArray) {
21210 return Array.isArray(thing);
21211 }
21212
21213 return Object.prototype.toString.call(thing) === '[object Array]';
21214 }
21215
21216 /**
21217 * Public function `date`.
21218 *
21219 * Returns `true` something is a date, `false` otherwise.
21220 *
21221 * @param thing The thing to test.
21222 */
21223 function date (thing) {
21224 return Object.prototype.toString.call(thing) === '[object Date]';
21225 }
21226
21227 /**
21228 * Public function `fn`.
21229 *
21230 * Returns `true` if something is function, `false` otherwise.
21231 *
21232 * @param thing The thing to test.
21233 */
21234 function fn (thing) {
21235 return typeof thing === 'function';
21236 }
21237
21238 /**
21239 * Public function `webUrl`.
21240 *
21241 * Returns `true` if something is an HTTP or HTTPS URL,
21242 * `false` otherwise.
21243 *
21244 * @param thing The thing to test.
21245 */
21246 function webUrl (thing) {
21247 return unemptyString(thing) && /^https?:\/\/.+/.test(thing);
21248 }
21249
21250 /**
21251 * Public function `gitUrl`.
21252 *
21253 * Returns `true` if something is a git+ssh, git+http or git+https URL,
21254 * `false` otherwise.
21255 *
21256 * @param thing The thing to test.
21257 */
21258 function gitUrl (thing) {
21259 return unemptyString(thing) && /^git\+(ssh|https?):\/\/.+/.test(thing);
21260 }
21261
21262 /**
21263 * Public function `email`.
21264 *
21265 * Returns `true` if something seems like a valid email address,
21266 * `false` otherwise.
21267 *
21268 * @param thing The thing to test.
21269 */
21270 function email (thing) {
21271 return unemptyString(thing) && /\S+@\S+/.test(thing);
21272 }
21273
21274 /**
21275 * Public function `unemptyString`.
21276 *
21277 * Returns `true` if something is a non-empty string, `false`
21278 * otherwise.
21279 *
21280 * @param thing The thing to test.
21281 */
21282 function unemptyString (thing) {
21283 return string(thing) && thing !== '';
21284 }
21285
21286 /**
21287 * Public function `string`.
21288 *
21289 * Returns `true` if something is a string, `false` otherwise.
21290 *
21291 * @param thing The thing to test.
21292 */
21293 function string (thing) {
21294 return typeof thing === 'string';
21295 }
21296
21297 /**
21298 * Public function `oddNumber`.
21299 *
21300 * Returns `true` if something is an odd number,
21301 * `false` otherwise.
21302 *
21303 * @param thing The thing to test.
21304 */
21305 function oddNumber (thing) {
21306 return number(thing) && (thing % 2 === 1 || thing % 2 === -1);
21307 }
21308
21309 /**
21310 * Public function `evenNumber`.
21311 *
21312 * Returns `true` if something is an even number,
21313 * `false` otherwise.
21314 *
21315 * @param thing The thing to test.
21316 */
21317 function evenNumber (thing) {
21318 return number(thing) && thing % 2 === 0;
21319 }
21320
21321 /**
21322 * Public function `intNumber`.
21323 *
21324 * Returns `true` if something is an integer number,
21325 * `false` otherwise.
21326 *
21327 * @param thing The thing to test.
21328 */
21329 function intNumber (thing) {
21330 return number(thing) && thing % 1 === 0;
21331 }
21332
21333 /**
21334 * Public function `floatNumber`.
21335 *
21336 * Returns `true` if something is a float number,
21337 * `false` otherwise.
21338 *
21339 * @param thing The thing to test.
21340 */
21341 function floatNumber (thing) {
21342 return number(thing) && thing % 1 !== 0;
21343 }
21344
21345 /**
21346 * Public function `positiveNumber`.
21347 *
21348 * Returns `true` if something is a positive number,
21349 * `false` otherwise.
21350 *
21351 * @param thing The thing to test.
21352 */
21353 function positiveNumber (thing) {
21354 return number(thing) && thing > 0;
21355 }
21356
21357 /**
21358 * Public function `negativeNumber`.
21359 *
21360 * Returns `true` if something is a positive number,
21361 * `false` otherwise.
21362 *
21363 * @param thing The thing to test.
21364 */
21365 function negativeNumber (thing) {
21366 return number(thing) && thing < 0;
21367 }
21368
21369 /**
21370 * Public function `number`.
21371 *
21372 * Returns `true` if something is a real number,
21373 * `false` otherwise.
21374 *
21375 * @param thing The thing to test.
21376 */
21377 function number (thing) {
21378 return typeof thing === 'number' &&
21379 isNaN(thing) === false &&
21380 thing !== Number.POSITIVE_INFINITY &&
21381 thing !== Number.NEGATIVE_INFINITY;
21382 }
21383
21384 /**
21385 * Public function `bool`.
21386 *
21387 * Returns `true` if something is a bool,
21388 * `false` otherwise.
21389 *
21390 * @param thing The thing to test.
21391 */
21392 function bool (thing) {
21393 return thing === false || thing === true;
21394 }
21395
21396 /**
21397 * Public function `map`.
21398 *
21399 * Returns the results hash of mapping each predicate to the
21400 * corresponding thing's property. Similar to `like` but
21401 * with functions instead of values.
21402 *
21403 * @param things {object} The things to test.
21404 * @param predicates {object} The map of functions to call against
21405 * the corresponding properties from `things`.
21406 */
21407 function map (things, predicates) {
21408 var property, result = {}, predicate;
21409
21410 verify.object(things);
21411 verify.object(predicates);
21412
21413 for (property in predicates) {
21414 if (predicates.hasOwnProperty(property)) {
21415 predicate = predicates[property];
21416
21417 if (fn(predicate)) {
21418 result[property] = predicate(things[property]);
21419 } else if (object(predicate)) {
21420 result[property] = map(things[property], predicate);
21421 }
21422 }
21423 }
21424
21425 return result;
21426 }
21427
21428 /**
21429 * Public function `every`
21430 *
21431 * Returns the conjunction of all booleans in a hash.
21432 *
21433 * @param predicateResults {object} The hash of evaluated predicates.
21434 */
21435 function every (predicateResults) {
21436 var property, value;
21437
21438 verify.object(predicateResults);
21439
21440 for (property in predicateResults) {
21441 if (predicateResults.hasOwnProperty(property)) {
21442 value = predicateResults[property];
21443
21444 if (object(value) && every(value) === false) {
21445 return false;
21446 }
21447
21448 if (value === false) {
21449 return false;
21450 }
21451 }
21452 }
21453 return true;
21454 }
21455
21456 /**
21457 * Public function `any`
21458 *
21459 * Returns the disjunction of all booleans in a hash.
21460 *
21461 * @param predicateResults {object} The hash of evaluated predicates.
21462 */
21463 function any (predicateResults) {
21464 var property, value;
21465
21466 verify.object(predicateResults);
21467
21468 for (property in predicateResults) {
21469 if (predicateResults.hasOwnProperty(property)) {
21470 value = predicateResults[property];
21471
21472 if (object(value) && any(value)) {
21473 return true;
21474 }
21475
21476 if (value === true) {
21477 return true;
21478 }
21479 }
21480 }
21481
21482 return false;
21483 }
21484
21485 function mixin (target, source) {
21486 var property;
21487
21488 for (property in source) {
21489 if (source.hasOwnProperty(property)) {
21490 target[property] = source[property];
21491 }
21492 }
21493
21494 return target;
21495 }
21496
21497 /**
21498 * Public modifier `verify`.
21499 *
21500 * Throws if `predicate` returns `false`.
21501 */
21502 function verifyModifier (predicate, defaultMessage) {
21503 return function () {
21504 var message;
21505
21506 if (predicate.apply(null, arguments) === false) {
21507 message = arguments[arguments.length - 1];
21508 throw new Error(unemptyString(message) ? message : defaultMessage);
21509 }
21510 };
21511 }
21512
21513 /**
21514 * Public modifier `maybe`.
21515 *
21516 * Returns `true` if `predicate` is `null` or `undefined`,
21517 * otherwise propagates the return value from `predicate`.
21518 */
21519 function maybeModifier (predicate) {
21520 return function () {
21521 if (!defined(arguments[0]) || nulled(arguments[0])) {
21522 return true;
21523 }
21524
21525 return predicate.apply(null, arguments);
21526 };
21527 }
21528
21529 /**
21530 * Public modifier `not`.
21531 *
21532 * Negates `predicate`.
21533 */
21534 function notModifier (predicate) {
21535 return function () {
21536 return !predicate.apply(null, arguments);
21537 };
21538 }
21539
21540 function createModifiedPredicates (modifier) {
21541 return createModifiedFunctions(modifier, predicates);
21542 }
21543
21544 function createModifiedFunctions (modifier, functions) {
21545 var name, result = {};
21546
21547 for (name in functions) {
21548 if (functions.hasOwnProperty(name)) {
21549 result[name] = modifier(functions[name], messages[name]);
21550 }
21551 }
21552
21553 return result;
21554 }
21555
21556 function exportFunctions (functions) {
21557 if (true) {
21558 !(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
21559 return functions;
21560 }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
21561 } else if (typeof module !== 'undefined' && module !== null && module.exports) {
21562 module.exports = functions;
21563 } else {
21564 globals.check = functions;
21565 }
21566 }
21567 }(this));
21568
21569
21570/***/ }
21571/******/ ])
21572});
21573;
\No newline at end of file