/**
* @license
- * lodash 3.10.1 (Custom Build) <https://lodash.com/>
- * Build: `lodash modern -o ./lodash.js`
- * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
+ * lodash 4.5.1 <https://lodash.com/>
+ * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
- * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
;(function() {
var undefined;
/** Used as the semantic version number. */
- var VERSION = '3.10.1';
+ var VERSION = '4.5.1';
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64,
ARY_FLAG = 128,
- REARG_FLAG = 256;
+ REARG_FLAG = 256,
+ FLIP_FLAG = 512;
- /** Used as default options for `_.trunc`. */
+ /** Used to compose bitmasks for comparison styles. */
+ var UNORDERED_COMPARE_FLAG = 1,
+ PARTIAL_COMPARE_FLAG = 2;
+
+ /** Used as default options for `_.truncate`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
- /** Used to detect when a function becomes hot. */
+ /** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 150,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_FILTER_FLAG = 1,
- LAZY_MAP_FLAG = 2;
+ LAZY_MAP_FLAG = 2,
+ LAZY_WHILE_FLAG = 3;
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
+ /** Used to stand-in for `undefined` hash values. */
+ var HASH_UNDEFINED = '__lodash_hash_undefined__';
+
+ /** Used as references for various `Number` constants. */
+ var INFINITY = 1 / 0,
+ MAX_SAFE_INTEGER = 9007199254740991,
+ MAX_INTEGER = 1.7976931348623157e+308,
+ NAN = 0 / 0;
+
+ /** Used as references for the maximum length and index of an array. */
+ var MAX_ARRAY_LENGTH = 4294967295,
+ MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
+ HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
+
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
+ genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
- weakMapTag = '[object WeakMap]';
+ symbolTag = '[object Symbol]',
+ weakMapTag = '[object WeakMap]',
+ weakSetTag = '[object WeakSet]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match property names within property paths. */
- var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
+ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/,
- rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
+ rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;
- /**
- * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
- * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
- */
- var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
- reHasRegExpChars = RegExp(reRegExpChars.source);
+ /** Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns). */
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
+ reHasRegExpChar = RegExp(reRegExpChar.source);
- /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
- var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
+ /** Used to match leading and trailing whitespace. */
+ var reTrim = /^\s+|\s+$/g,
+ reTrimStart = /^\s+/,
+ reTrimEnd = /\s+$/;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
var reFlags = /\w*$/;
/** Used to detect hexadecimal string values. */
- var reHasHexPrefix = /^0[xX]/;
+ var reHasHexPrefix = /^0x/i;
+
+ /** Used to detect bad signed hexadecimal string values. */
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
+
+ /** Used to detect binary string values. */
+ var reIsBinary = /^0b[01]+$/i;
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
+ /** Used to detect octal string values. */
+ var reIsOctal = /^0o[0-7]+$/i;
+
/** Used to detect unsigned integer values. */
- var reIsUint = /^\d+$/;
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to match latin-1 supplementary letters (excluding mathematical operators). */
var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
- /** Used to match words to create compound words. */
- var reWords = (function() {
- var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
- lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
+ /** Used to compose unicode character classes. */
+ var rsAstralRange = '\\ud800-\\udfff',
+ rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
+ rsComboSymbolsRange = '\\u20d0-\\u20f0',
+ rsDingbatRange = '\\u2700-\\u27bf',
+ rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
+ rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
+ rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
+ rsQuoteRange = '\\u2018\\u2019\\u201c\\u201d',
+ rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
+ rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
+ rsVarRange = '\\ufe0e\\ufe0f',
+ rsBreakRange = rsMathOpRange + rsNonCharRange + rsQuoteRange + rsSpaceRange;
+
+ /** Used to compose unicode capture groups. */
+ var rsAstral = '[' + rsAstralRange + ']',
+ rsBreak = '[' + rsBreakRange + ']',
+ rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
+ rsDigits = '\\d+',
+ rsDingbat = '[' + rsDingbatRange + ']',
+ rsLower = '[' + rsLowerRange + ']',
+ rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
+ rsFitz = '\\ud83c[\\udffb-\\udfff]',
+ rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
+ rsNonAstral = '[^' + rsAstralRange + ']',
+ rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
+ rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
+ rsUpper = '[' + rsUpperRange + ']',
+ rsZWJ = '\\u200d';
+
+ /** Used to compose unicode regexes. */
+ var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
+ rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
+ reOptMod = rsModifier + '?',
+ rsOptVar = '[' + rsVarRange + ']?',
+ rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
+ rsSeq = rsOptVar + reOptMod + rsOptJoin,
+ rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
+ rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
- return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
- }());
+ /**
+ * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
+ * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
+ */
+ var reComboMark = RegExp(rsCombo, 'g');
+
+ /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
+ var reComplexSymbol = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
+
+ /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
+ var reHasComplexSymbol = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
+
+ /** Used to match non-compound words composed of alphanumeric characters. */
+ var reBasicWord = /[a-zA-Z0-9]+/g;
+
+ /** Used to match complex or compound words. */
+ var reComplexWord = RegExp([
+ rsUpper + '?' + rsLower + '+(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
+ rsUpperMisc + '+(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
+ rsUpper + '?' + rsLowerMisc + '+',
+ rsUpper + '+',
+ rsDigits,
+ rsEmoji
+ ].join('|'), 'g');
+
+ /** Used to detect strings that need a more robust regexp to match words. */
+ var reHasComplexWord = /[a-z][A-Z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/** Used to assign default `context` object properties. */
var contextProps = [
- 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
- 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
- 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite',
- 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
- 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap'
+ 'Array', 'Buffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
+ 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
+ 'Reflect', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
+ 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_',
+ 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
];
/** Used to make template sourceURLs easier to identify. */
cloneableTags[dateTag] = cloneableTags[float32Tag] =
cloneableTags[float64Tag] = cloneableTags[int8Tag] =
cloneableTags[int16Tag] = cloneableTags[int32Tag] =
- cloneableTags[numberTag] = cloneableTags[objectTag] =
- cloneableTags[regexpTag] = cloneableTags[stringTag] =
- cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
- cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
+ cloneableTags[mapTag] = cloneableTags[numberTag] =
+ cloneableTags[objectTag] = cloneableTags[regexpTag] =
+ cloneableTags[setTag] = cloneableTags[stringTag] =
+ cloneableTags[symbolTag] = cloneableTags[uint8Tag] =
+ cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] =
+ cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
- cloneableTags[mapTag] = cloneableTags[setTag] =
cloneableTags[weakMapTag] = false;
/** Used to map latin-1 supplementary letters to basic latin letters. */
'object': true
};
- /** Used to escape characters for inclusion in compiled regexes. */
- var regexpEscapes = {
- '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34',
- '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39',
- 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46',
- 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66',
- 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78'
- };
-
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
'\u2029': 'u2029'
};
+ /** Built-in method references without a dependency on `root`. */
+ var freeParseFloat = parseFloat,
+ freeParseInt = parseInt;
+
/** Detect free variable `exports`. */
- var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
+ var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
+ ? exports
+ : undefined;
/** Detect free variable `module`. */
- var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
+ var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
+ ? module
+ : undefined;
+
+ /** Detect the popular CommonJS extension `module.exports`. */
+ var moduleExports = (freeModule && freeModule.exports === freeExports)
+ ? freeExports
+ : undefined;
/** Detect free variable `global` from Node.js. */
- var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
+ var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
/** Detect free variable `self`. */
- var freeSelf = objectTypes[typeof self] && self && self.Object && self;
+ var freeSelf = checkGlobal(objectTypes[typeof self] && self);
/** Detect free variable `window`. */
- var freeWindow = objectTypes[typeof window] && window && window.Object && window;
+ var freeWindow = checkGlobal(objectTypes[typeof window] && window);
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
+ /** Detect `this` as the global object. */
+ var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
/**
* Used as a reference to the global object.
* The `this` value is used if it's the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
- var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
+ var root = freeGlobal ||
+ ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
+ freeSelf || thisGlobal || Function('return this')();
/*--------------------------------------------------------------------------*/
/**
- * The base implementation of `compareAscending` which compares values and
- * sorts them in ascending order without guaranteeing a stable sort.
+ * Adds the key-value `pair` to `map`.
*
* @private
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {number} Returns the sort order indicator for `value`.
+ * @param {Object} map The map to modify.
+ * @param {Array} pair The key-value pair to add.
+ * @returns {Object} Returns `map`.
*/
- function baseCompareAscending(value, other) {
- if (value !== other) {
- var valIsNull = value === null,
- valIsUndef = value === undefined,
- valIsReflexive = value === value;
+ function addMapEntry(map, pair) {
+ map.set(pair[0], pair[1]);
+ return map;
+ }
- var othIsNull = other === null,
- othIsUndef = other === undefined,
- othIsReflexive = other === other;
+ /**
+ * Adds `value` to `set`.
+ *
+ * @private
+ * @param {Object} set The set to modify.
+ * @param {*} value The value to add.
+ * @returns {Object} Returns `set`.
+ */
+ function addSetEntry(set, value) {
+ set.add(value);
+ return set;
+ }
- if ((value > other && !othIsNull) || !valIsReflexive ||
- (valIsNull && !othIsUndef && othIsReflexive) ||
- (valIsUndef && othIsReflexive)) {
- return 1;
+ /**
+ * A faster alternative to `Function#apply`, this function invokes `func`
+ * with the `this` binding of `thisArg` and the arguments of `args`.
+ *
+ * @private
+ * @param {Function} func The function to invoke.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {...*} args The arguments to invoke `func` with.
+ * @returns {*} Returns the result of `func`.
+ */
+ function apply(func, thisArg, args) {
+ var length = args.length;
+ switch (length) {
+ case 0: return func.call(thisArg);
+ case 1: return func.call(thisArg, args[0]);
+ case 2: return func.call(thisArg, args[0], args[1]);
+ case 3: return func.call(thisArg, args[0], args[1], args[2]);
+ }
+ return func.apply(thisArg, args);
+ }
+
+ /**
+ * A specialized version of `baseAggregator` for arrays.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} setter The function to set `accumulator` values.
+ * @param {Function} iteratee The iteratee to transform keys.
+ * @param {Object} accumulator The initial aggregated object.
+ * @returns {Function} Returns `accumulator`.
+ */
+ function arrayAggregator(array, setter, iteratee, accumulator) {
+ var index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ var value = array[index];
+ setter(accumulator, value, iteratee(value), array);
+ }
+ return accumulator;
+ }
+
+ /**
+ * Creates a new array concatenating `array` with `other`.
+ *
+ * @private
+ * @param {Array} array The first array to concatenate.
+ * @param {Array} other The second array to concatenate.
+ * @returns {Array} Returns the new concatenated array.
+ */
+ function arrayConcat(array, other) {
+ var index = -1,
+ length = array.length,
+ othIndex = -1,
+ othLength = other.length,
+ result = Array(length + othLength);
+
+ while (++index < length) {
+ result[index] = array[index];
+ }
+ while (++othIndex < othLength) {
+ result[index++] = other[othIndex];
+ }
+ return result;
+ }
+
+ /**
+ * A specialized version of `_.forEach` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayEach(array, iteratee) {
+ var index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ if (iteratee(array[index], index, array) === false) {
+ break;
}
- if ((value < other && !valIsNull) || !othIsReflexive ||
- (othIsNull && !valIsUndef && valIsReflexive) ||
- (othIsUndef && valIsReflexive)) {
- return -1;
+ }
+ return array;
+ }
+
+ /**
+ * A specialized version of `_.forEachRight` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayEachRight(array, iteratee) {
+ var length = array.length;
+
+ while (length--) {
+ if (iteratee(array[length], length, array) === false) {
+ break;
}
}
- return 0;
+ return array;
+ }
+
+ /**
+ * A specialized version of `_.every` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check, else `false`.
+ */
+ function arrayEvery(array, predicate) {
+ var index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ if (!predicate(array[index], index, array)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * A specialized version of `_.filter` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {Array} Returns the new filtered array.
+ */
+ function arrayFilter(array, predicate) {
+ var index = -1,
+ length = array.length,
+ resIndex = -1,
+ result = [];
+
+ while (++index < length) {
+ var value = array[index];
+ if (predicate(value, index, array)) {
+ result[++resIndex] = value;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * A specialized version of `_.includes` for arrays without support for
+ * specifying an index to search from.
+ *
+ * @private
+ * @param {Array} array The array to search.
+ * @param {*} target The value to search for.
+ * @returns {boolean} Returns `true` if `target` is found, else `false`.
+ */
+ function arrayIncludes(array, value) {
+ return !!array.length && baseIndexOf(array, value, 0) > -1;
+ }
+
+ /**
+ * A specialized version of `_.includesWith` for arrays without support for
+ * specifying an index to search from.
+ *
+ * @private
+ * @param {Array} array The array to search.
+ * @param {*} target The value to search for.
+ * @param {Function} comparator The comparator invoked per element.
+ * @returns {boolean} Returns `true` if `target` is found, else `false`.
+ */
+ function arrayIncludesWith(array, value, comparator) {
+ var index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ if (comparator(value, array[index])) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * A specialized version of `_.map` for arrays without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the new mapped array.
+ */
+ function arrayMap(array, iteratee) {
+ var index = -1,
+ length = array.length,
+ result = Array(length);
+
+ while (++index < length) {
+ result[index] = iteratee(array[index], index, array);
+ }
+ return result;
+ }
+
+ /**
+ * Appends the elements of `values` to `array`.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to append.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayPush(array, values) {
+ var index = -1,
+ length = values.length,
+ offset = array.length;
+
+ while (++index < length) {
+ array[offset + index] = values[index];
+ }
+ return array;
+ }
+
+ /**
+ * A specialized version of `_.reduce` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @param {boolean} [initAccum] Specify using the first element of `array` as the initial value.
+ * @returns {*} Returns the accumulated value.
+ */
+ function arrayReduce(array, iteratee, accumulator, initAccum) {
+ var index = -1,
+ length = array.length;
+
+ if (initAccum && length) {
+ accumulator = array[++index];
+ }
+ while (++index < length) {
+ accumulator = iteratee(accumulator, array[index], index, array);
+ }
+ return accumulator;
+ }
+
+ /**
+ * A specialized version of `_.reduceRight` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @param {boolean} [initAccum] Specify using the last element of `array` as the initial value.
+ * @returns {*} Returns the accumulated value.
+ */
+ function arrayReduceRight(array, iteratee, accumulator, initAccum) {
+ var length = array.length;
+ if (initAccum && length) {
+ accumulator = array[--length];
+ }
+ while (length--) {
+ accumulator = iteratee(accumulator, array[length], length, array);
+ }
+ return accumulator;
+ }
+
+ /**
+ * A specialized version of `_.some` for arrays without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`.
+ */
+ function arraySome(array, predicate) {
+ var index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ if (predicate(array[index], index, array)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * The base implementation of methods like `_.max` and `_.min` which accepts a
+ * `comparator` to determine the extremum value.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The iteratee invoked per iteration.
+ * @param {Function} comparator The comparator used to compare values.
+ * @returns {*} Returns the extremum value.
+ */
+ function baseExtremum(array, iteratee, comparator) {
+ var index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ var value = array[index],
+ current = iteratee(value);
+
+ if (current != null && (computed === undefined
+ ? current === current
+ : comparator(current, computed)
+ )) {
+ var computed = current,
+ result = value;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * The base implementation of methods like `_.find` and `_.findKey`, without
+ * support for iteratee shorthands, which iterates over `collection` using
+ * `eachFunc`.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to search.
+ * @param {Function} predicate The function invoked per iteration.
+ * @param {Function} eachFunc The function to iterate over `collection`.
+ * @param {boolean} [retKey] Specify returning the key of the found element instead of the element itself.
+ * @returns {*} Returns the found element or its key, else `undefined`.
+ */
+ function baseFind(collection, predicate, eachFunc, retKey) {
+ var result;
+ eachFunc(collection, function(value, key, collection) {
+ if (predicate(value, key, collection)) {
+ result = retKey ? key : value;
+ return false;
+ }
+ });
+ return result;
}
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
- * support for callback shorthands and `this` binding.
+ * support for iteratee shorthands.
*
* @private
* @param {Array} array The array to search.
}
/**
- * The base implementation of `_.indexOf` without support for binary searches.
+ * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to search.
}
/**
- * The base implementation of `_.isFunction` without support for environments
- * with incorrect `typeof` results.
+ * The base implementation of `_.reduce` and `_.reduceRight`, without support
+ * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} accumulator The initial value.
+ * @param {boolean} initAccum Specify using the first or last element of `collection` as the initial value.
+ * @param {Function} eachFunc The function to iterate over `collection`.
+ * @returns {*} Returns the accumulated value.
*/
- function baseIsFunction(value) {
- // Avoid a Chakra JIT bug in compatibility modes of IE 11.
- // See https://github.com/jashkenas/underscore/issues/1621 for more details.
- return typeof value == 'function' || false;
+ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
+ eachFunc(collection, function(value, index, collection) {
+ accumulator = initAccum
+ ? (initAccum = false, value)
+ : iteratee(accumulator, value, index, collection);
+ });
+ return accumulator;
}
/**
- * Converts `value` to a string if it's not one. An empty string is returned
- * for `null` or `undefined` values.
+ * The base implementation of `_.sortBy` which uses `comparer` to define
+ * the sort order of `array` and replaces criteria objects with their
+ * corresponding values.
*
* @private
- * @param {*} value The value to process.
- * @returns {string} Returns the string.
+ * @param {Array} array The array to sort.
+ * @param {Function} comparer The function to define sort order.
+ * @returns {Array} Returns `array`.
*/
- function baseToString(value) {
- return value == null ? '' : (value + '');
+ function baseSortBy(array, comparer) {
+ var length = array.length;
+
+ array.sort(comparer);
+ while (length--) {
+ array[length] = array[length].value;
+ }
+ return array;
}
/**
- * Used by `_.trim` and `_.trimLeft` to get the index of the first character
- * of `string` that is not found in `chars`.
+ * The base implementation of `_.sum` without support for iteratee shorthands.
*
* @private
- * @param {string} string The string to inspect.
- * @param {string} chars The characters to find.
- * @returns {number} Returns the index of the first character not found in `chars`.
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {number} Returns the sum.
+ */
+ function baseSum(array, iteratee) {
+ var result,
+ index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ var current = iteratee(array[index]);
+ if (current !== undefined) {
+ result = result === undefined ? current : (result + current);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.times` without support for iteratee shorthands
+ * or max array length checks.
+ *
+ * @private
+ * @param {number} n The number of times to invoke `iteratee`.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the array of results.
+ */
+ function baseTimes(n, iteratee) {
+ var index = -1,
+ result = Array(n);
+
+ while (++index < n) {
+ result[index] = iteratee(index);
+ }
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
+ * of key-value pairs for `object` corresponding to the property names of `props`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} props The property names to get values for.
+ * @returns {Object} Returns the new array of key-value pairs.
+ */
+ function baseToPairs(object, props) {
+ return arrayMap(props, function(key) {
+ return [key, object[key]];
+ });
+ }
+
+ /**
+ * The base implementation of `_.unary` without support for storing wrapper metadata.
+ *
+ * @private
+ * @param {Function} func The function to cap arguments for.
+ * @returns {Function} Returns the new function.
+ */
+ function baseUnary(func) {
+ return function(value) {
+ return func(value);
+ };
+ }
+
+ /**
+ * The base implementation of `_.values` and `_.valuesIn` which creates an
+ * array of `object` property values corresponding to the property names
+ * of `props`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} props The property names to get values for.
+ * @returns {Object} Returns the array of property values.
+ */
+ function baseValues(object, props) {
+ return arrayMap(props, function(key) {
+ return object[key];
+ });
+ }
+
+ /**
+ * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
+ * that is not found in the character symbols.
+ *
+ * @private
+ * @param {Array} strSymbols The string symbols to inspect.
+ * @param {Array} chrSymbols The character symbols to find.
+ * @returns {number} Returns the index of the first unmatched string symbol.
*/
- function charsLeftIndex(string, chars) {
+ function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
- length = string.length;
+ length = strSymbols.length;
- while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
+ while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
- * Used by `_.trim` and `_.trimRight` to get the index of the last character
- * of `string` that is not found in `chars`.
+ * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
+ * that is not found in the character symbols.
*
* @private
- * @param {string} string The string to inspect.
- * @param {string} chars The characters to find.
- * @returns {number} Returns the index of the last character not found in `chars`.
+ * @param {Array} strSymbols The string symbols to inspect.
+ * @param {Array} chrSymbols The character symbols to find.
+ * @returns {number} Returns the index of the last unmatched string symbol.
*/
- function charsRightIndex(string, chars) {
- var index = string.length;
+ function charsEndIndex(strSymbols, chrSymbols) {
+ var index = strSymbols.length;
- while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
+ while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
- * Used by `_.sortBy` to compare transformed elements of a collection and stable
- * sort them in ascending order.
+ * Checks if `value` is a global object.
*
* @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @returns {number} Returns the sort order indicator for `object`.
+ * @param {*} value The value to check.
+ * @returns {null|Object} Returns `value` if it's a global object, else `null`.
*/
- function compareAscending(object, other) {
- return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
+ function checkGlobal(value) {
+ return (value && value.Object === Object) ? value : null;
}
/**
- * Used by `_.sortByOrder` to compare multiple properties of a value to another
+ * Compares values to sort them in ascending order.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {number} Returns the sort order indicator for `value`.
+ */
+ function compareAscending(value, other) {
+ if (value !== other) {
+ var valIsNull = value === null,
+ valIsUndef = value === undefined,
+ valIsReflexive = value === value;
+
+ var othIsNull = other === null,
+ othIsUndef = other === undefined,
+ othIsReflexive = other === other;
+
+ if ((value > other && !othIsNull) || !valIsReflexive ||
+ (valIsNull && !othIsUndef && othIsReflexive) ||
+ (valIsUndef && othIsReflexive)) {
+ return 1;
+ }
+ if ((value < other && !valIsNull) || !othIsReflexive ||
+ (othIsNull && !valIsUndef && valIsReflexive) ||
+ (othIsUndef && valIsReflexive)) {
+ return -1;
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
- * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
- * a value is sorted in ascending order if its corresponding order is "asc", and
- * descending if "desc".
+ * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
+ * specify an order of "desc" for descending or "asc" for ascending sort order
+ * of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
- * @param {boolean[]} orders The order to sort by for each property.
+ * @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
ordersLength = orders.length;
while (++index < length) {
- var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
+ var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
- return result * ((order === 'asc' || order === true) ? 1 : -1);
+ return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
}
/**
+ * Gets the number of `placeholder` occurrences in `array`.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {*} placeholder The placeholder to search for.
+ * @returns {number} Returns the placeholder count.
+ */
+ function countHolders(array, placeholder) {
+ var length = array.length,
+ result = 0;
+
+ while (length--) {
+ if (array[length] === placeholder) {
+ result++;
+ }
+ }
+ return result;
+ }
+
+ /**
* Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
*
* @private
}
/**
- * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
- *
- * @private
- * @param {string} chr The matched character to escape.
- * @param {string} leadingChar The capture group for a leading character.
- * @param {string} whitespaceChar The capture group for a whitespace character.
- * @returns {string} Returns the escaped character.
- */
- function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
- if (leadingChar) {
- chr = regexpEscapes[chr];
- } else if (whitespaceChar) {
- chr = stringEscapes[chr];
- }
- return '\\' + chr;
- }
-
- /**
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
}
/**
- * Checks if `value` is object-like.
+ * Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
+ * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
+ */
+ function isHostObject(value) {
+ // Many host objects are `Object` objects that can coerce to strings
+ // despite having improperly defined `toString` methods.
+ var result = false;
+ if (value != null && typeof value.toString != 'function') {
+ try {
+ result = !!(value + '');
+ } catch (e) {}
+ }
+ return result;
+ }
+
+ /**
+ * Checks if `value` is a valid array-like index.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
+ * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
+ */
+ function isIndex(value, length) {
+ value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
+ length = length == null ? MAX_SAFE_INTEGER : length;
+ return value > -1 && value % 1 == 0 && value < length;
+ }
+
+ /**
+ * Converts `iterator` to an array.
+ *
+ * @private
+ * @param {Object} iterator The iterator to convert.
+ * @returns {Array} Returns the converted array.
*/
- function isObjectLike(value) {
- return !!value && typeof value == 'object';
+ function iteratorToArray(iterator) {
+ var data,
+ result = [];
+
+ while (!(data = iterator.next()).done) {
+ result.push(data.value);
+ }
+ return result;
}
/**
- * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
- * character code is whitespace.
+ * Converts `map` to an array.
*
* @private
- * @param {number} charCode The character code to inspect.
- * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
+ * @param {Object} map The map to convert.
+ * @returns {Array} Returns the converted array.
*/
- function isSpace(charCode) {
- return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
- (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
+ function mapToArray(map) {
+ var index = -1,
+ result = Array(map.size);
+
+ map.forEach(function(value, key) {
+ result[++index] = [key, value];
+ });
+ return result;
}
/**
result = [];
while (++index < length) {
- if (array[index] === placeholder) {
+ var value = array[index];
+ if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[++resIndex] = index;
}
}
/**
- * An implementation of `_.uniq` optimized for sorted arrays without support
- * for callback shorthands and `this` binding.
+ * Converts `set` to an array.
*
* @private
- * @param {Array} array The array to inspect.
- * @param {Function} [iteratee] The function invoked per iteration.
- * @returns {Array} Returns the new duplicate free array.
+ * @param {Object} set The set to convert.
+ * @returns {Array} Returns the converted array.
*/
- function sortedUniq(array, iteratee) {
- var seen,
- index = -1,
- length = array.length,
- resIndex = -1,
- result = [];
-
- while (++index < length) {
- var value = array[index],
- computed = iteratee ? iteratee(value, index, array) : value;
+ function setToArray(set) {
+ var index = -1,
+ result = Array(set.size);
- if (!index || seen !== computed) {
- seen = computed;
- result[++resIndex] = value;
- }
- }
+ set.forEach(function(value) {
+ result[++index] = value;
+ });
return result;
}
/**
- * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
- * character of `string`.
+ * Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
- * @returns {number} Returns the index of the first non-whitespace character.
+ * @returns {number} Returns the string size.
*/
- function trimmedLeftIndex(string) {
- var index = -1,
- length = string.length;
-
- while (++index < length && isSpace(string.charCodeAt(index))) {}
- return index;
+ function stringSize(string) {
+ if (!(string && reHasComplexSymbol.test(string))) {
+ return string.length;
+ }
+ var result = reComplexSymbol.lastIndex = 0;
+ while (reComplexSymbol.test(string)) {
+ result++;
+ }
+ return result;
}
/**
- * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
- * character of `string`.
+ * Converts `string` to an array.
*
* @private
- * @param {string} string The string to inspect.
- * @returns {number} Returns the index of the last non-whitespace character.
+ * @param {string} string The string to convert.
+ * @returns {Array} Returns the converted array.
*/
- function trimmedRightIndex(string) {
- var index = string.length;
-
- while (index-- && isSpace(string.charCodeAt(index))) {}
- return index;
+ function stringToArray(string) {
+ return string.match(reComplexSymbol);
}
/**
/*--------------------------------------------------------------------------*/
/**
- * Create a new pristine `lodash` function using the given `context` object.
+ * Create a new pristine `lodash` function using the `context` object.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
* lodash.isFunction(lodash.bar);
* // => true
*
- * // using `context` to mock `Date#getTime` use in `_.now`
+ * // Use `context` to mock `Date#getTime` use in `_.now`.
* var mock = _.runInContext({
* 'Date': function() {
* return { 'getTime': getTimeMock };
* }
* });
*
- * // or creating a suped-up `defer` in Node.js
+ * // Create a suped-up `defer` in Node.js.
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
*/
function runInContext(context) {
- // Avoid issues with some ES3 environments that attempt to use values, named
- // after built-in constructors like `Object`, for the creation of literals.
- // ES5 clears this up by stating that literals must use built-in constructors.
- // See https://es5.github.io/#x11.1.5 for more details.
- context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
-
- /** Native constructor references. */
- var Array = context.Array,
- Date = context.Date,
+ context = context ? _.defaults({}, context, _.pick(root, contextProps)) : root;
+
+ /** Built-in constructor references. */
+ var Date = context.Date,
Error = context.Error,
- Function = context.Function,
Math = context.Math,
- Number = context.Number,
- Object = context.Object,
RegExp = context.RegExp,
- String = context.String,
TypeError = context.TypeError;
- /** Used for native method references. */
- var arrayProto = Array.prototype,
- objectProto = Object.prototype,
- stringProto = String.prototype;
+ /** Used for built-in method references. */
+ var arrayProto = context.Array.prototype,
+ objectProto = context.Object.prototype;
/** Used to resolve the decompiled source of functions. */
- var fnToString = Function.prototype.toString;
+ var funcToString = context.Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
+ /** Used to infer the `Object` constructor. */
+ var objectCtorString = funcToString.call(Object);
+
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
- var objToString = objectProto.toString;
+ var objectToString = objectProto.toString;
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = root._;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
- fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
+ funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
- /** Native method references. */
- var ArrayBuffer = context.ArrayBuffer,
+ /** Built-in value references. */
+ var Buffer = moduleExports ? context.Buffer : undefined,
+ Reflect = context.Reflect,
+ Symbol = context.Symbol,
+ Uint8Array = context.Uint8Array,
clearTimeout = context.clearTimeout,
- parseFloat = context.parseFloat,
- pow = Math.pow,
+ enumerate = Reflect ? Reflect.enumerate : undefined,
+ getPrototypeOf = Object.getPrototypeOf,
+ getOwnPropertySymbols = Object.getOwnPropertySymbols,
+ iteratorSymbol = typeof (iteratorSymbol = Symbol && Symbol.iterator) == 'symbol' ? iteratorSymbol : undefined,
+ objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
- Set = getNative(context, 'Set'),
setTimeout = context.setTimeout,
- splice = arrayProto.splice,
- Uint8Array = context.Uint8Array,
- WeakMap = getNative(context, 'WeakMap');
+ splice = arrayProto.splice;
- /* Native method references for those with the same name as other `lodash` methods. */
+ /* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
- nativeCreate = getNative(Object, 'create'),
nativeFloor = Math.floor,
- nativeIsArray = getNative(Array, 'isArray'),
nativeIsFinite = context.isFinite,
- nativeKeys = getNative(Object, 'keys'),
+ nativeJoin = arrayProto.join,
+ nativeKeys = Object.keys,
nativeMax = Math.max,
nativeMin = Math.min,
- nativeNow = getNative(Date, 'now'),
nativeParseInt = context.parseInt,
- nativeRandom = Math.random;
+ nativeRandom = Math.random,
+ nativeReverse = arrayProto.reverse;
- /** Used as references for `-Infinity` and `Infinity`. */
- var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
- POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
-
- /** Used as references for the maximum length and index of an array. */
- var MAX_ARRAY_LENGTH = 4294967295,
- MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
- HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
-
- /**
- * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
- * of an array-like value.
- */
- var MAX_SAFE_INTEGER = 9007199254740991;
+ /* Built-in method references that are verified to be native. */
+ var Map = getNative(context, 'Map'),
+ Set = getNative(context, 'Set'),
+ WeakMap = getNative(context, 'WeakMap'),
+ nativeCreate = getNative(Object, 'create');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
+ /** Used to detect maps, sets, and weakmaps. */
+ var mapCtorString = Map ? funcToString.call(Map) : '',
+ setCtorString = Set ? funcToString.call(Set) : '',
+ weakMapCtorString = WeakMap ? funcToString.call(WeakMap) : '';
+
+ /** Used to convert symbols to primitives and strings. */
+ var symbolProto = Symbol ? Symbol.prototype : undefined,
+ symbolValueOf = Symbol ? symbolProto.valueOf : undefined,
+ symbolToString = Symbol ? symbolProto.toString : undefined;
+
/** Used to lookup unminified function names. */
var realNames = {};
/*------------------------------------------------------------------------*/
/**
- * Creates a `lodash` object which wraps `value` to enable implicit chaining.
- * Methods that operate on and return arrays, collections, and functions can
- * be chained together. Methods that retrieve a single value or may return a
- * primitive value will automatically end the chain returning the unwrapped
- * value. Explicit chaining may be enabled using `_.chain`. The execution of
- * chained methods is lazy, that is, execution is deferred until `_#value`
- * is implicitly or explicitly called.
+ * Creates a `lodash` object which wraps `value` to enable implicit method
+ * chaining. Methods that operate on and return arrays, collections, and
+ * functions can be chained together. Methods that retrieve a single value or
+ * may return a primitive value will automatically end the chain sequence and
+ * return the unwrapped value. Otherwise, the value must be unwrapped with
+ * `_#value`.
+ *
+ * Explicit chaining, which must be unwrapped with `_#value` in all cases,
+ * may be enabled using `_.chain`.
+ *
+ * The execution of chained methods is lazy, that is, it's deferred until
+ * `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion. Shortcut
- * fusion is an optimization strategy which merge iteratee calls; this can help
- * to avoid the creation of intermediate data structures and greatly reduce the
- * number of iteratee executions.
+ * fusion is an optimization to merge iteratee calls; this avoids the creation
+ * of intermediate arrays and can greatly reduce the number of iteratee executions.
+ * Sections of a chain sequence qualify for shortcut fusion if the section is
+ * applied to an array of at least two hundred elements and any iteratees
+ * accept only one argument. The heuristic for whether a section qualifies
+ * for shortcut fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
- * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
- * `splice`, and `unshift`
+ * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
- * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
- * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
- * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
- * and `where`
+ * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
+ * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
+ * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
- * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
- * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
- * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
- * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
- * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
- * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
- * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
- * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
- * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
- * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
- * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
- * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
- * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
- * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
- * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
- * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
- * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
+ * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
+ * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
+ * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
+ * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, `difference`,
+ * `differenceBy`, `differenceWith`, `drop`, `dropRight`, `dropRightWhile`,
+ * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flattenDepth`,
+ * `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, `functionsIn`,
+ * `groupBy`, `initial`, `intersection`, `intersectionBy`, `intersectionWith`,
+ * `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, `keys`, `keysIn`,
+ * `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, `memoize`,
+ * `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, `nthArg`,
+ * `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, `overEvery`,
+ * `overSome`, `partial`, `partialRight`, `partition`, `pick`, `pickBy`, `plant`,
+ * `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, `pullAt`, `push`,
+ * `range`, `rangeRight`, `rearg`, `reject`, `remove`, `rest`, `reverse`,
+ * `sampleSize`, `set`, `setWith`, `shuffle`, `slice`, `sort`, `sortBy`,
+ * `splice`, `spread`, `tail`, `take`, `takeRight`, `takeRightWhile`,
+ * `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, `toPairs`, `toPairsIn`,
+ * `toPath`, `toPlainObject`, `transform`, `unary`, `union`, `unionBy`,
+ * `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, `unshift`, `unzip`,
+ * `unzipWith`, `values`, `valuesIn`, `without`, `wrap`, `xor`, `xorBy`,
+ * `xorWith`, `zip`, `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
- * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
- * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
- * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
- * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
- * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
- * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
- * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
- * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
- * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
- * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
- * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
- * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
- * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
- * `unescape`, `uniqueId`, `value`, and `words`
- *
- * The wrapper method `sample` will return a wrapped value when `n` is provided,
- * otherwise an unwrapped value is returned.
+ * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
+ * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `deburr`, `endsWith`, `eq`,
+ * `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
+ * `findLastIndex`, `findLastKey`, `floor`, `forEach`, `forEachRight`, `forIn`,
+ * `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, `hasIn`,
+ * `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, `isArguments`,
+ * `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, `isBoolean`,
+ * `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isEqualWith`,
+ * `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, `isMap`,
+ * `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, `isNumber`,
+ * `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, `isSafeInteger`,
+ * `isSet`, `isString`, `isUndefined`, `isTypedArray`, `isWeakMap`, `isWeakSet`,
+ * `join`, `kebabCase`, `last`, `lastIndexOf`, `lowerCase`, `lowerFirst`,
+ * `lt`, `lte`, `max`, `maxBy`, `mean`, `min`, `minBy`, `noConflict`, `noop`,
+ * `now`, `pad`, `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`,
+ * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `sample`,
+ * `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`,
+ * `sortedLastIndex`, `sortedLastIndexBy`, `startCase`, `startsWith`, `subtract`,
+ * `sum`, `sumBy`, `template`, `times`, `toLower`, `toInteger`, `toLength`,
+ * `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, `trimEnd`,
+ * `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, `upperFirst`,
+ * `value`, and `words`
*
* @name _
* @constructor
- * @category Chain
+ * @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
+ * function square(n) {
+ * return n * n;
+ * }
+ *
* var wrapped = _([1, 2, 3]);
*
- * // returns an unwrapped value
- * wrapped.reduce(function(total, n) {
- * return total + n;
- * });
+ * // Returns an unwrapped value.
+ * wrapped.reduce(_.add);
* // => 6
*
- * // returns a wrapped value
- * var squares = wrapped.map(function(n) {
- * return n * n;
- * });
+ * // Returns a wrapped value.
+ * var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
if (value instanceof LodashWrapper) {
return value;
}
- if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
+ if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable chaining for all wrapper methods.
- * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
*/
- function LodashWrapper(value, chainAll, actions) {
+ function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
- this.__actions__ = actions || [];
+ this.__actions__ = [];
this.__chain__ = !!chainAll;
+ this.__index__ = 0;
+ this.__values__ = undefined;
}
/**
- * An object environment feature flags.
- *
- * @static
- * @memberOf _
- * @type Object
- */
- var support = lodash.support = {};
-
- /**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB). Change the following template settings to use
* alternative delimiters.
*
* @static
* @memberOf _
- * @type Object
+ * @type {Object}
*/
lodash.templateSettings = {
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
- * @type RegExp
+ * @type {RegExp}
*/
'escape': reEscape,
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
- * @type RegExp
+ * @type {RegExp}
*/
'evaluate': reEvaluate,
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
- * @type RegExp
+ * @type {RegExp}
*/
'interpolate': reInterpolate,
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
- * @type string
+ * @type {string}
*/
'variable': '',
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
- * @type Object
+ * @type {Object}
*/
'imports': {
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
- * @type Function
+ * @type {Function}
*/
'_': lodash
}
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
+ * @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
- this.__takeCount__ = POSITIVE_INFINITY;
+ this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
*/
function lazyClone() {
var result = new LazyWrapper(this.__wrapped__);
- result.__actions__ = arrayCopy(this.__actions__);
+ result.__actions__ = copyArray(this.__actions__);
result.__dir__ = this.__dir__;
result.__filtered__ = this.__filtered__;
- result.__iteratees__ = arrayCopy(this.__iteratees__);
+ result.__iteratees__ = copyArray(this.__iteratees__);
result.__takeCount__ = this.__takeCount__;
- result.__views__ = arrayCopy(this.__views__);
+ result.__views__ = copyArray(this.__views__);
return result;
}
resIndex = 0,
takeCount = nativeMin(length, this.__takeCount__);
- if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) {
+ if (!isArr || arrLength < LARGE_ARRAY_SIZE ||
+ (arrLength == length && takeCount == length)) {
return baseWrapperValue(array, this.__actions__);
}
var result = [];
/*------------------------------------------------------------------------*/
/**
- * Creates a cache object to store key/value pairs.
+ * Creates an hash object.
*
* @private
- * @static
- * @name Cache
- * @memberOf _.memoize
+ * @constructor
+ * @returns {Object} Returns the new hash object.
+ */
+ function Hash() {}
+
+ /**
+ * Removes `key` and its value from the hash.
+ *
+ * @private
+ * @param {Object} hash The hash to modify.
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
+ function hashDelete(hash, key) {
+ return hashHas(hash, key) && delete hash[key];
+ }
+
+ /**
+ * Gets the hash value for `key`.
+ *
+ * @private
+ * @param {Object} hash The hash to query.
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
*/
- function MapCache() {
- this.__data__ = {};
+ function hashGet(hash, key) {
+ if (nativeCreate) {
+ var result = hash[key];
+ return result === HASH_UNDEFINED ? undefined : result;
+ }
+ return hasOwnProperty.call(hash, key) ? hash[key] : undefined;
}
/**
- * Removes `key` and its value from the cache.
+ * Checks if a hash value for `key` exists.
+ *
+ * @private
+ * @param {Object} hash The hash to query.
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
+ function hashHas(hash, key) {
+ return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key);
+ }
+
+ /**
+ * Sets the hash `key` to `value`.
+ *
+ * @private
+ * @param {Object} hash The hash to modify.
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ */
+ function hashSet(hash, key, value) {
+ hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Creates a map cache object to store key-value pairs.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [values] The values to cache.
+ */
+ function MapCache(values) {
+ var index = -1,
+ length = values ? values.length : 0;
+
+ this.clear();
+ while (++index < length) {
+ var entry = values[index];
+ this.set(entry[0], entry[1]);
+ }
+ }
+
+ /**
+ * Removes all key-value entries from the map.
+ *
+ * @private
+ * @name clear
+ * @memberOf MapCache
+ */
+ function mapClear() {
+ this.__data__ = {
+ 'hash': new Hash,
+ 'map': Map ? new Map : [],
+ 'string': new Hash
+ };
+ }
+
+ /**
+ * Removes `key` and its value from the map.
*
* @private
* @name delete
- * @memberOf _.memoize.Cache
+ * @memberOf MapCache
* @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapDelete(key) {
- return this.has(key) && delete this.__data__[key];
+ var data = this.__data__;
+ if (isKeyable(key)) {
+ return hashDelete(typeof key == 'string' ? data.string : data.hash, key);
+ }
+ return Map ? data.map['delete'](key) : assocDelete(data.map, key);
}
/**
- * Gets the cached value for `key`.
+ * Gets the map value for `key`.
*
* @private
* @name get
- * @memberOf _.memoize.Cache
+ * @memberOf MapCache
* @param {string} key The key of the value to get.
- * @returns {*} Returns the cached value.
+ * @returns {*} Returns the entry value.
*/
function mapGet(key) {
- return key == '__proto__' ? undefined : this.__data__[key];
+ var data = this.__data__;
+ if (isKeyable(key)) {
+ return hashGet(typeof key == 'string' ? data.string : data.hash, key);
+ }
+ return Map ? data.map.get(key) : assocGet(data.map, key);
}
/**
- * Checks if a cached value for `key` exists.
+ * Checks if a map value for `key` exists.
*
* @private
* @name has
- * @memberOf _.memoize.Cache
+ * @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapHas(key) {
- return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
+ var data = this.__data__;
+ if (isKeyable(key)) {
+ return hashHas(typeof key == 'string' ? data.string : data.hash, key);
+ }
+ return Map ? data.map.has(key) : assocHas(data.map, key);
}
/**
- * Sets `value` to `key` of the cache.
+ * Sets the map `key` to `value`.
*
* @private
* @name set
- * @memberOf _.memoize.Cache
- * @param {string} key The key of the value to cache.
- * @param {*} value The value to cache.
- * @returns {Object} Returns the cache object.
+ * @memberOf MapCache
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the map cache object.
*/
function mapSet(key, value) {
- if (key != '__proto__') {
- this.__data__[key] = value;
+ var data = this.__data__;
+ if (isKeyable(key)) {
+ hashSet(typeof key == 'string' ? data.string : data.hash, key, value);
+ } else if (Map) {
+ data.map.set(key, value);
+ } else {
+ assocSet(data.map, key, value);
}
return this;
}
/**
*
- * Creates a cache object to store unique values.
+ * Creates a set cache object to store unique values.
*
* @private
+ * @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
- var length = values ? values.length : 0;
+ var index = -1,
+ length = values ? values.length : 0;
- this.data = { 'hash': nativeCreate(null), 'set': new Set };
- while (length--) {
- this.push(values[length]);
+ this.__data__ = new MapCache;
+ while (++index < length) {
+ this.push(values[index]);
}
}
/**
- * Checks if `value` is in `cache` mimicking the return signature of
- * `_.indexOf` by returning `0` if the value is found, else `-1`.
+ * Checks if `value` is in `cache`.
*
* @private
- * @param {Object} cache The cache to search.
+ * @param {Object} cache The set cache to search.
* @param {*} value The value to search for.
- * @returns {number} Returns `0` if `value` is found, else `-1`.
+ * @returns {number} Returns `true` if `value` is found, else `false`.
*/
- function cacheIndexOf(cache, value) {
- var data = cache.data,
- result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
+ function cacheHas(cache, value) {
+ var map = cache.__data__;
+ if (isKeyable(value)) {
+ var data = map.__data__,
+ hash = typeof value == 'string' ? data.string : data.hash;
- return result ? 0 : -1;
+ return hash[value] === HASH_UNDEFINED;
+ }
+ return map.has(value);
}
/**
- * Adds `value` to the cache.
+ * Adds `value` to the set cache.
*
* @private
* @name push
* @param {*} value The value to cache.
*/
function cachePush(value) {
- var data = this.data;
- if (typeof value == 'string' || isObject(value)) {
- data.set.add(value);
- } else {
- data.hash[value] = true;
+ var map = this.__data__;
+ if (isKeyable(value)) {
+ var data = map.__data__,
+ hash = typeof value == 'string' ? data.string : data.hash;
+
+ hash[value] = HASH_UNDEFINED;
+ }
+ else {
+ map.set(value, HASH_UNDEFINED);
}
}
/*------------------------------------------------------------------------*/
/**
- * Creates a new array joining `array` with `other`.
+ * Creates a stack cache object to store key-value pairs.
*
* @private
- * @param {Array} array The array to join.
- * @param {Array} other The other array to join.
- * @returns {Array} Returns the new concatenated array.
+ * @constructor
+ * @param {Array} [values] The values to cache.
*/
- function arrayConcat(array, other) {
+ function Stack(values) {
var index = -1,
- length = array.length,
- othIndex = -1,
- othLength = other.length,
- result = Array(length + othLength);
+ length = values ? values.length : 0;
+ this.clear();
while (++index < length) {
- result[index] = array[index];
+ var entry = values[index];
+ this.set(entry[0], entry[1]);
}
- while (++othIndex < othLength) {
- result[index++] = other[othIndex];
- }
- return result;
}
/**
- * Copies the values of `source` to `array`.
+ * Removes all key-value entries from the stack.
*
* @private
- * @param {Array} source The array to copy values from.
- * @param {Array} [array=[]] The array to copy values to.
- * @returns {Array} Returns `array`.
+ * @name clear
+ * @memberOf Stack
*/
- function arrayCopy(source, array) {
- var index = -1,
- length = source.length;
-
- array || (array = Array(length));
- while (++index < length) {
- array[index] = source[index];
- }
- return array;
+ function stackClear() {
+ this.__data__ = { 'array': [], 'map': null };
}
/**
- * A specialized version of `_.forEach` for arrays without support for callback
- * shorthands and `this` binding.
+ * Removes `key` and its value from the stack.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns `array`.
+ * @name delete
+ * @memberOf Stack
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
- function arrayEach(array, iteratee) {
- var index = -1,
- length = array.length;
+ function stackDelete(key) {
+ var data = this.__data__,
+ array = data.array;
- while (++index < length) {
- if (iteratee(array[index], index, array) === false) {
- break;
- }
- }
- return array;
+ return array ? assocDelete(array, key) : data.map['delete'](key);
}
/**
- * A specialized version of `_.forEachRight` for arrays without support for
- * callback shorthands and `this` binding.
+ * Gets the stack value for `key`.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns `array`.
+ * @name get
+ * @memberOf Stack
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
*/
- function arrayEachRight(array, iteratee) {
- var length = array.length;
+ function stackGet(key) {
+ var data = this.__data__,
+ array = data.array;
- while (length--) {
- if (iteratee(array[length], length, array) === false) {
- break;
- }
- }
- return array;
+ return array ? assocGet(array, key) : data.map.get(key);
}
/**
- * A specialized version of `_.every` for arrays without support for callback
- * shorthands and `this` binding.
+ * Checks if a stack value for `key` exists.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if all elements pass the predicate check,
- * else `false`.
+ * @name has
+ * @memberOf Stack
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
- function arrayEvery(array, predicate) {
- var index = -1,
- length = array.length;
+ function stackHas(key) {
+ var data = this.__data__,
+ array = data.array;
- while (++index < length) {
- if (!predicate(array[index], index, array)) {
- return false;
- }
- }
- return true;
+ return array ? assocHas(array, key) : data.map.has(key);
}
/**
- * A specialized version of `baseExtremum` for arrays which invokes `iteratee`
- * with one argument: (value).
+ * Sets the stack `key` to `value`.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {Function} comparator The function used to compare values.
- * @param {*} exValue The initial extremum value.
- * @returns {*} Returns the extremum value.
+ * @name set
+ * @memberOf Stack
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the stack cache object.
*/
- function arrayExtremum(array, iteratee, comparator, exValue) {
- var index = -1,
- length = array.length,
- computed = exValue,
- result = computed;
+ function stackSet(key, value) {
+ var data = this.__data__,
+ array = data.array;
- while (++index < length) {
- var value = array[index],
- current = +iteratee(value);
-
- if (comparator(current, computed)) {
- computed = current;
- result = value;
+ if (array) {
+ if (array.length < (LARGE_ARRAY_SIZE - 1)) {
+ assocSet(array, key, value);
+ } else {
+ data.array = null;
+ data.map = new MapCache(array);
}
}
- return result;
- }
-
- /**
- * A specialized version of `_.filter` for arrays without support for callback
- * shorthands and `this` binding.
- *
- * @private
- * @param {Array} array The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {Array} Returns the new filtered array.
- */
- function arrayFilter(array, predicate) {
- var index = -1,
- length = array.length,
- resIndex = -1,
- result = [];
-
- while (++index < length) {
- var value = array[index];
- if (predicate(value, index, array)) {
- result[++resIndex] = value;
- }
+ var map = data.map;
+ if (map) {
+ map.set(key, value);
}
- return result;
+ return this;
}
+ /*------------------------------------------------------------------------*/
+
/**
- * A specialized version of `_.map` for arrays without support for callback
- * shorthands and `this` binding.
+ * Removes `key` and its value from the associative array.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the new mapped array.
+ * @param {Array} array The array to query.
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
- function arrayMap(array, iteratee) {
- var index = -1,
- length = array.length,
- result = Array(length);
-
- while (++index < length) {
- result[index] = iteratee(array[index], index, array);
+ function assocDelete(array, key) {
+ var index = assocIndexOf(array, key);
+ if (index < 0) {
+ return false;
}
- return result;
+ var lastIndex = array.length - 1;
+ if (index == lastIndex) {
+ array.pop();
+ } else {
+ splice.call(array, index, 1);
+ }
+ return true;
}
/**
- * Appends the elements of `values` to `array`.
+ * Gets the associative array value for `key`.
*
* @private
- * @param {Array} array The array to modify.
- * @param {Array} values The values to append.
- * @returns {Array} Returns `array`.
+ * @param {Array} array The array to query.
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
*/
- function arrayPush(array, values) {
- var index = -1,
- length = values.length,
- offset = array.length;
-
- while (++index < length) {
- array[offset + index] = values[index];
- }
- return array;
+ function assocGet(array, key) {
+ var index = assocIndexOf(array, key);
+ return index < 0 ? undefined : array[index][1];
}
/**
- * A specialized version of `_.reduce` for arrays without support for callback
- * shorthands and `this` binding.
+ * Checks if an associative array value for `key` exists.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {*} [accumulator] The initial value.
- * @param {boolean} [initFromArray] Specify using the first element of `array`
- * as the initial value.
- * @returns {*} Returns the accumulated value.
+ * @param {Array} array The array to query.
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
- function arrayReduce(array, iteratee, accumulator, initFromArray) {
- var index = -1,
- length = array.length;
-
- if (initFromArray && length) {
- accumulator = array[++index];
- }
- while (++index < length) {
- accumulator = iteratee(accumulator, array[index], index, array);
- }
- return accumulator;
+ function assocHas(array, key) {
+ return assocIndexOf(array, key) > -1;
}
/**
- * A specialized version of `_.reduceRight` for arrays without support for
- * callback shorthands and `this` binding.
+ * Gets the index at which the first occurrence of `key` is found in `array`
+ * of key-value pairs.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {*} [accumulator] The initial value.
- * @param {boolean} [initFromArray] Specify using the last element of `array`
- * as the initial value.
- * @returns {*} Returns the accumulated value.
+ * @param {Array} array The array to search.
+ * @param {*} key The key to search for.
+ * @returns {number} Returns the index of the matched value, else `-1`.
*/
- function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
+ function assocIndexOf(array, key) {
var length = array.length;
- if (initFromArray && length) {
- accumulator = array[--length];
- }
while (length--) {
- accumulator = iteratee(accumulator, array[length], length, array);
+ if (eq(array[length][0], key)) {
+ return length;
+ }
}
- return accumulator;
+ return -1;
}
/**
- * A specialized version of `_.some` for arrays without support for callback
- * shorthands and `this` binding.
+ * Sets the associative array `key` to `value`.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if any element passes the predicate check,
- * else `false`.
+ * @param {Array} array The array to modify.
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
*/
- function arraySome(array, predicate) {
- var index = -1,
- length = array.length;
-
- while (++index < length) {
- if (predicate(array[index], index, array)) {
- return true;
- }
+ function assocSet(array, key, value) {
+ var index = assocIndexOf(array, key);
+ if (index < 0) {
+ array.push([key, value]);
+ } else {
+ array[index][1] = value;
}
- return false;
}
+ /*------------------------------------------------------------------------*/
+
/**
- * A specialized version of `_.sum` for arrays without support for callback
- * shorthands and `this` binding..
+ * Used by `_.defaults` to customize its `_.assignIn` use.
*
* @private
- * @param {Array} array The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {number} Returns the sum.
+ * @param {*} objValue The destination value.
+ * @param {*} srcValue The source value.
+ * @param {string} key The key of the property to assign.
+ * @param {Object} object The parent object of `objValue`.
+ * @returns {*} Returns the value to assign.
*/
- function arraySum(array, iteratee) {
- var length = array.length,
- result = 0;
-
- while (length--) {
- result += +iteratee(array[length]) || 0;
+ function assignInDefaults(objValue, srcValue, key, object) {
+ if (objValue === undefined ||
+ (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
+ return srcValue;
}
- return result;
+ return objValue;
}
/**
- * Used by `_.defaults` to customize its `_.assign` use.
+ * This function is like `assignValue` except that it doesn't assign `undefined` values.
*
* @private
- * @param {*} objectValue The destination object property value.
- * @param {*} sourceValue The source object property value.
- * @returns {*} Returns the value to assign to the destination object.
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
*/
- function assignDefaults(objectValue, sourceValue) {
- return objectValue === undefined ? sourceValue : objectValue;
+ function assignMergeValue(object, key, value) {
+ if ((value !== undefined && !eq(object[key], value)) ||
+ (typeof key == 'number' && value === undefined && !(key in object))) {
+ object[key] = value;
+ }
}
/**
- * Used by `_.template` to customize its `_.assign` use.
- *
- * **Note:** This function is like `assignDefaults` except that it ignores
- * inherited property values when checking if a property is `undefined`.
+ * Assigns `value` to `key` of `object` if the existing value is not equivalent
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons.
*
* @private
- * @param {*} objectValue The destination object property value.
- * @param {*} sourceValue The source object property value.
- * @param {string} key The key associated with the object and source values.
- * @param {Object} object The destination object.
- * @returns {*} Returns the value to assign to the destination object.
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
*/
- function assignOwnDefaults(objectValue, sourceValue, key, object) {
- return (objectValue === undefined || !hasOwnProperty.call(object, key))
- ? sourceValue
- : objectValue;
+ function assignValue(object, key, value) {
+ var objValue = object[key];
+ if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
+ (value === undefined && !(key in object))) {
+ object[key] = value;
+ }
}
/**
- * A specialized version of `_.assign` for customizing assigned values without
- * support for argument juggling, multiple sources, and `this` binding `customizer`
- * functions.
+ * Aggregates elements of `collection` on `accumulator` with keys transformed
+ * by `iteratee` and values set by `setter`.
*
* @private
- * @param {Object} object The destination object.
- * @param {Object} source The source object.
- * @param {Function} customizer The function to customize assigned values.
- * @returns {Object} Returns `object`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} setter The function to set `accumulator` values.
+ * @param {Function} iteratee The iteratee to transform keys.
+ * @param {Object} accumulator The initial aggregated object.
+ * @returns {Function} Returns `accumulator`.
*/
- function assignWith(object, source, customizer) {
- var index = -1,
- props = keys(source),
- length = props.length;
-
- while (++index < length) {
- var key = props[index],
- value = object[key],
- result = customizer(value, source[key], key, object, source);
-
- if ((result === result ? (result !== value) : (value === value)) ||
- (value === undefined && !(key in object))) {
- object[key] = result;
- }
- }
- return object;
+ function baseAggregator(collection, setter, iteratee, accumulator) {
+ baseEach(collection, function(value, key, collection) {
+ setter(accumulator, value, iteratee(value), collection);
+ });
+ return accumulator;
}
/**
- * The base implementation of `_.assign` without support for argument juggling,
- * multiple sources, and `customizer` functions.
+ * The base implementation of `_.assign` without support for multiple sources
+ * or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
- return source == null
- ? object
- : baseCopy(source, keys(source), object);
+ return object && copyObject(source, keys(source), object);
}
/**
- * The base implementation of `_.at` without support for string collections
- * and individual key arguments.
+ * The base implementation of `_.at` without support for individual paths.
*
* @private
- * @param {Array|Object} collection The collection to iterate over.
- * @param {number[]|string[]} props The property names or indexes of elements to pick.
+ * @param {Object} object The object to iterate over.
+ * @param {string[]} paths The property paths of elements to pick.
* @returns {Array} Returns the new array of picked elements.
*/
- function baseAt(collection, props) {
+ function baseAt(object, paths) {
var index = -1,
- isNil = collection == null,
- isArr = !isNil && isArrayLike(collection),
- length = isArr ? collection.length : 0,
- propsLength = props.length,
- result = Array(propsLength);
+ isNil = object == null,
+ length = paths.length,
+ result = Array(length);
- while(++index < propsLength) {
- var key = props[index];
- if (isArr) {
- result[index] = isIndex(key, length) ? collection[key] : undefined;
- } else {
- result[index] = isNil ? undefined : collection[key];
- }
+ while (++index < length) {
+ result[index] = isNil ? undefined : get(object, paths[index]);
}
return result;
}
/**
- * Copies properties of `source` to `object`.
+ * Casts `value` to an empty array if it's not an array like object.
*
* @private
- * @param {Object} source The object to copy properties from.
- * @param {Array} props The property names to copy.
- * @param {Object} [object={}] The object to copy properties to.
- * @returns {Object} Returns `object`.
+ * @param {*} value The value to inspect.
+ * @returns {Array} Returns the array-like object.
*/
- function baseCopy(source, props, object) {
- object || (object = {});
+ function baseCastArrayLikeObject(value) {
+ return isArrayLikeObject(value) ? value : [];
+ }
- var index = -1,
- length = props.length;
+ /**
+ * Casts `value` to `identity` if it's not a function.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @returns {Array} Returns the array-like object.
+ */
+ function baseCastFunction(value) {
+ return typeof value == 'function' ? value : identity;
+ }
- while (++index < length) {
- var key = props[index];
- object[key] = source[key];
- }
- return object;
+ /**
+ * Casts `value` to a path array if it's not one.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @returns {Array} Returns the cast property path array.
+ */
+ function baseCastPath(value) {
+ return isArray(value) ? value : stringToPath(value);
}
/**
- * The base implementation of `_.callback` which supports specifying the
- * number of arguments to provide to `func`.
+ * The base implementation of `_.clamp` which doesn't coerce arguments to numbers.
*
* @private
- * @param {*} [func=_.identity] The value to convert to a callback.
- * @param {*} [thisArg] The `this` binding of `func`.
- * @param {number} [argCount] The number of arguments to provide to `func`.
- * @returns {Function} Returns the callback.
+ * @param {number} number The number to clamp.
+ * @param {number} [lower] The lower bound.
+ * @param {number} upper The upper bound.
+ * @returns {number} Returns the clamped number.
*/
- function baseCallback(func, thisArg, argCount) {
- var type = typeof func;
- if (type == 'function') {
- return thisArg === undefined
- ? func
- : bindCallback(func, thisArg, argCount);
- }
- if (func == null) {
- return identity;
- }
- if (type == 'object') {
- return baseMatches(func);
+ function baseClamp(number, lower, upper) {
+ if (number === number) {
+ if (upper !== undefined) {
+ number = number <= upper ? number : upper;
+ }
+ if (lower !== undefined) {
+ number = number >= lower ? number : lower;
+ }
}
- return thisArg === undefined
- ? property(func)
- : baseMatchesProperty(func, thisArg);
+ return number;
}
/**
- * The base implementation of `_.clone` without support for argument juggling
- * and `this` binding `customizer` functions.
+ * The base implementation of `_.clone` and `_.cloneDeep` which tracks
+ * traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
- * @param {Function} [customizer] The function to customize cloning values.
+ * @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
- * @param {Object} [object] The object `value` belongs to.
- * @param {Array} [stackA=[]] Tracks traversed source objects.
- * @param {Array} [stackB=[]] Associates clones with source counterparts.
+ * @param {Object} [object] The parent object of `value`.
+ * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
- function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
+ function baseClone(value, isDeep, customizer, key, object, stack) {
var result;
if (customizer) {
- result = object ? customizer(value, key, object) : customizer(value);
+ result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
- return arrayCopy(value, result);
+ return copyArray(value, result);
}
} else {
- var tag = objToString.call(value),
- isFunc = tag == funcTag;
+ var tag = getTag(value),
+ isFunc = tag == funcTag || tag == genTag;
+ if (isBuffer(value)) {
+ return cloneBuffer(value, isDeep);
+ }
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
+ if (isHostObject(value)) {
+ return object ? value : {};
+ }
result = initCloneObject(isFunc ? {} : value);
if (!isDeep) {
- return baseAssign(result, value);
+ return copySymbols(value, baseAssign(result, value));
}
} else {
- return cloneableTags[tag]
- ? initCloneByTag(value, tag, isDeep)
- : (object ? value : {});
+ if (!cloneableTags[tag]) {
+ return object ? value : {};
+ }
+ result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
- stackA || (stackA = []);
- stackB || (stackB = []);
-
- var length = stackA.length;
- while (length--) {
- if (stackA[length] == value) {
- return stackB[length];
- }
+ stack || (stack = new Stack);
+ var stacked = stack.get(value);
+ if (stacked) {
+ return stacked;
}
- // Add the source value to the stack of traversed objects and associate it with its clone.
- stackA.push(value);
- stackB.push(result);
+ stack.set(value, result);
// Recursively populate clone (susceptible to call stack limits).
(isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
- result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
+ assignValue(result, key, baseClone(subValue, isDeep, customizer, key, value, stack));
});
- return result;
+ return isArr ? result : copySymbols(value, result);
+ }
+
+ /**
+ * The base implementation of `_.conforms` which doesn't clone `source`.
+ *
+ * @private
+ * @param {Object} source The object of property predicates to conform to.
+ * @returns {Function} Returns the new function.
+ */
+ function baseConforms(source) {
+ var props = keys(source),
+ length = props.length;
+
+ return function(object) {
+ if (object == null) {
+ return !length;
+ }
+ var index = length;
+ while (index--) {
+ var key = props[index],
+ predicate = source[key],
+ value = object[key];
+
+ if ((value === undefined && !(key in Object(object))) || !predicate(value)) {
+ return false;
+ }
+ }
+ return true;
+ };
}
/**
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
- var baseCreate = (function() {
- function object() {}
- return function(prototype) {
- if (isObject(prototype)) {
- object.prototype = prototype;
- var result = new object;
- object.prototype = undefined;
- }
- return result || {};
- };
- }());
+ function baseCreate(proto) {
+ return isObject(proto) ? objectCreate(proto) : {};
+ }
/**
- * The base implementation of `_.delay` and `_.defer` which accepts an index
- * of where to slice the arguments to provide to `func`.
+ * The base implementation of `_.delay` and `_.defer` which accepts an array
+ * of `func` arguments.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
- * @param {Object} args The arguments provide to `func`.
+ * @param {Object} args The arguments to provide to `func`.
* @returns {number} Returns the timer id.
*/
function baseDelay(func, wait, args) {
}
/**
- * The base implementation of `_.difference` which accepts a single array
- * of values to exclude.
+ * The base implementation of methods like `_.difference` without support for
+ * excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
- function baseDifference(array, values) {
- var length = array ? array.length : 0,
- result = [];
+ function baseDifference(array, values, iteratee, comparator) {
+ var index = -1,
+ includes = arrayIncludes,
+ isCommon = true,
+ length = array.length,
+ result = [],
+ valuesLength = values.length;
if (!length) {
return result;
}
- var index = -1,
- indexOf = getIndexOf(),
- isCommon = indexOf === baseIndexOf,
- cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null,
- valuesLength = values.length;
-
- if (cache) {
- indexOf = cacheIndexOf;
+ if (iteratee) {
+ values = arrayMap(values, baseUnary(iteratee));
+ }
+ if (comparator) {
+ includes = arrayIncludesWith;
isCommon = false;
- values = cache;
+ }
+ else if (values.length >= LARGE_ARRAY_SIZE) {
+ includes = cacheHas;
+ isCommon = false;
+ values = new SetCache(values);
}
outer:
while (++index < length) {
- var value = array[index];
+ var value = array[index],
+ computed = iteratee ? iteratee(value) : value;
- if (isCommon && value === value) {
+ if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
- if (values[valuesIndex] === value) {
+ if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
- else if (indexOf(values, value, 0) < 0) {
+ else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
}
/**
- * The base implementation of `_.forEach` without support for callback
- * shorthands and `this` binding.
+ * The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
- * @returns {Array|Object|string} Returns `collection`.
+ * @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
- * The base implementation of `_.forEachRight` without support for callback
- * shorthands and `this` binding.
+ * The base implementation of `_.forEachRight` without support for iteratee shorthands.
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
- * @returns {Array|Object|string} Returns `collection`.
+ * @returns {Array|Object} Returns `collection`.
*/
var baseEachRight = createBaseEach(baseForOwnRight, true);
/**
- * The base implementation of `_.every` without support for callback
- * shorthands and `this` binding.
+ * The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if all elements pass the predicate check,
- * else `false`
+ * @returns {boolean} Returns `true` if all elements pass the predicate check, else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
}
/**
- * Gets the extremum value of `collection` invoking `iteratee` for each value
- * in `collection` to generate the criterion by which the value is ranked.
- * The `iteratee` is invoked with three arguments: (value, index|key, collection).
- *
- * @private
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {Function} comparator The function used to compare values.
- * @param {*} exValue The initial extremum value.
- * @returns {*} Returns the extremum value.
- */
- function baseExtremum(collection, iteratee, comparator, exValue) {
- var computed = exValue,
- result = computed;
-
- baseEach(collection, function(value, index, collection) {
- var current = +iteratee(value, index, collection);
- if (comparator(current, computed) || (current === exValue && current === result)) {
- computed = current;
- result = value;
- }
- });
- return result;
- }
-
- /**
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
function baseFill(array, value, start, end) {
var length = array.length;
- start = start == null ? 0 : (+start || 0);
+ start = toInteger(start);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
- end = (end === undefined || end > length) ? length : (+end || 0);
+ end = (end === undefined || end > length) ? length : toInteger(end);
if (end < 0) {
end += length;
}
- length = start > end ? 0 : (end >>> 0);
- start >>>= 0;
-
- while (start < length) {
+ end = start > end ? 0 : toLength(end);
+ while (start < end) {
array[start++] = value;
}
return array;
}
/**
- * The base implementation of `_.filter` without support for callback
- * shorthands and `this` binding.
+ * The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
}
/**
- * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
- * without support for callback shorthands and `this` binding, which iterates
- * over `collection` using the provided `eachFunc`.
- *
- * @private
- * @param {Array|Object|string} collection The collection to search.
- * @param {Function} predicate The function invoked per iteration.
- * @param {Function} eachFunc The function to iterate over `collection`.
- * @param {boolean} [retKey] Specify returning the key of the found element
- * instead of the element itself.
- * @returns {*} Returns the found element or its key, else `undefined`.
- */
- function baseFind(collection, predicate, eachFunc, retKey) {
- var result;
- eachFunc(collection, function(value, key, collection) {
- if (predicate(value, key, collection)) {
- result = retKey ? key : value;
- return false;
- }
- });
- return result;
- }
-
- /**
- * The base implementation of `_.flatten` with added support for restricting
- * flattening and specifying the start index.
+ * The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
- * @param {boolean} [isDeep] Specify a deep flatten.
+ * @param {number} depth The maximum recursion depth.
* @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
- function baseFlatten(array, isDeep, isStrict, result) {
+ function baseFlatten(array, depth, isStrict, result) {
result || (result = []);
var index = -1,
while (++index < length) {
var value = array[index];
- if (isObjectLike(value) && isArrayLike(value) &&
+ if (depth > 0 && isArrayLikeObject(value) &&
(isStrict || isArray(value) || isArguments(value))) {
- if (isDeep) {
+ if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
- baseFlatten(value, isDeep, isStrict, result);
+ baseFlatten(value, depth - 1, isStrict, result);
} else {
arrayPush(result, value);
}
var baseForRight = createBaseFor(true);
/**
- * The base implementation of `_.forIn` without support for callback
- * shorthands and `this` binding.
+ * The base implementation of `_.forIn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @returns {Object} Returns `object`.
*/
function baseForIn(object, iteratee) {
- return baseFor(object, iteratee, keysIn);
+ return object == null ? object : baseFor(object, iteratee, keysIn);
}
/**
- * The base implementation of `_.forOwn` without support for callback
- * shorthands and `this` binding.
+ * The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
- return baseFor(object, iteratee, keys);
+ return object && baseFor(object, iteratee, keys);
}
/**
- * The base implementation of `_.forOwnRight` without support for callback
- * shorthands and `this` binding.
+ * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
- return baseForRight(object, iteratee, keys);
+ return object && baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
- * `object` function property names filtered from those provided.
+ * `object` function property names filtered from `props`.
*
* @private
* @param {Object} object The object to inspect.
* @returns {Array} Returns the new array of filtered property names.
*/
function baseFunctions(object, props) {
- var index = -1,
- length = props.length,
- resIndex = -1,
- result = [];
-
- while (++index < length) {
- var key = props[index];
- if (isFunction(object[key])) {
- result[++resIndex] = key;
- }
- }
- return result;
+ return arrayFilter(props, function(key) {
+ return isFunction(object[key]);
+ });
}
/**
- * The base implementation of `get` without support for string paths
- * and default values.
+ * The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
- * @param {Array} path The path of the property to get.
- * @param {string} [pathKey] The key representation of path.
+ * @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
- function baseGet(object, path, pathKey) {
- if (object == null) {
- return;
- }
- if (pathKey !== undefined && pathKey in toObject(object)) {
- path = [pathKey];
- }
+ function baseGet(object, path) {
+ path = isKey(path, object) ? [path + ''] : baseCastPath(path);
+
var index = 0,
length = path.length;
}
/**
- * The base implementation of `_.isEqual` without support for `this` binding
- * `customizer` functions.
+ * The base implementation of `_.has` without support for deep paths.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} key The key to check.
+ * @returns {boolean} Returns `true` if `key` exists, else `false`.
+ */
+ function baseHas(object, key) {
+ // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
+ // that are composed entirely of index properties, return `false` for
+ // `hasOwnProperty` checks of them.
+ return hasOwnProperty.call(object, key) ||
+ (typeof object == 'object' && key in object && getPrototypeOf(object) === null);
+ }
+
+ /**
+ * The base implementation of `_.hasIn` without support for deep paths.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} key The key to check.
+ * @returns {boolean} Returns `true` if `key` exists, else `false`.
+ */
+ function baseHasIn(object, key) {
+ return key in Object(object);
+ }
+
+ /**
+ * The base implementation of `_.inRange` which doesn't coerce arguments to numbers.
+ *
+ * @private
+ * @param {number} number The number to check.
+ * @param {number} start The start of the range.
+ * @param {number} end The end of the range.
+ * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
+ */
+ function baseInRange(number, start, end) {
+ return number >= nativeMin(start, end) && number < nativeMax(start, end);
+ }
+
+ /**
+ * The base implementation of methods like `_.intersection`, without support
+ * for iteratee shorthands, that accepts an array of arrays to inspect.
+ *
+ * @private
+ * @param {Array} arrays The arrays to inspect.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of shared values.
+ */
+ function baseIntersection(arrays, iteratee, comparator) {
+ var includes = comparator ? arrayIncludesWith : arrayIncludes,
+ othLength = arrays.length,
+ othIndex = othLength,
+ caches = Array(othLength),
+ result = [];
+
+ while (othIndex--) {
+ var array = arrays[othIndex];
+ if (othIndex && iteratee) {
+ array = arrayMap(array, baseUnary(iteratee));
+ }
+ caches[othIndex] = !comparator && (iteratee || array.length >= 120)
+ ? new SetCache(othIndex && array)
+ : undefined;
+ }
+ array = arrays[0];
+
+ var index = -1,
+ length = array.length,
+ seen = caches[0];
+
+ outer:
+ while (++index < length) {
+ var value = array[index],
+ computed = iteratee ? iteratee(value) : value;
+
+ if (!(seen
+ ? cacheHas(seen, computed)
+ : includes(result, computed, comparator)
+ )) {
+ var othIndex = othLength;
+ while (--othIndex) {
+ var cache = caches[othIndex];
+ if (!(cache
+ ? cacheHas(cache, computed)
+ : includes(arrays[othIndex], computed, comparator))
+ ) {
+ continue outer;
+ }
+ }
+ if (seen) {
+ seen.push(computed);
+ }
+ result.push(value);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.invert` and `_.invertBy` which inverts
+ * `object` with values transformed by `iteratee` and set by `setter`.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} setter The function to set `accumulator` values.
+ * @param {Function} iteratee The iteratee to transform values.
+ * @param {Object} accumulator The initial inverted object.
+ * @returns {Function} Returns `accumulator`.
+ */
+ function baseInverter(object, setter, iteratee, accumulator) {
+ baseForOwn(object, function(value, key, object) {
+ setter(accumulator, iteratee(value), key, object);
+ });
+ return accumulator;
+ }
+
+ /**
+ * The base implementation of `_.invoke` without support for individual
+ * method arguments.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the method to invoke.
+ * @param {Array} args The arguments to invoke the method with.
+ * @returns {*} Returns the result of the invoked method.
+ */
+ function baseInvoke(object, path, args) {
+ if (!isKey(path, object)) {
+ path = baseCastPath(path);
+ object = parent(object, path);
+ path = last(path);
+ }
+ var func = object == null ? object : object[path];
+ return func == null ? undefined : apply(func, object, args);
+ }
+
+ /**
+ * The base implementation of `_.isEqual` which supports partial comparisons
+ * and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
- * @param {Function} [customizer] The function to customize comparing values.
- * @param {boolean} [isLoose] Specify performing partial comparisons.
- * @param {Array} [stackA] Tracks traversed `value` objects.
- * @param {Array} [stackB] Tracks traversed `other` objects.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @param {boolean} [bitmask] The bitmask of comparison flags.
+ * The bitmask may be composed of the following flags:
+ * 1 - Unordered comparison
+ * 2 - Partial comparison
+ * @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
- function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
+ function baseIsEqual(value, other, customizer, bitmask, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
- return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
+ return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
}
/**
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} [customizer] The function to customize comparing objects.
- * @param {boolean} [isLoose] Specify performing partial comparisons.
- * @param {Array} [stackA=[]] Tracks traversed `value` objects.
- * @param {Array} [stackB=[]] Tracks traversed `other` objects.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` for more details.
+ * @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
- function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
+ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
- objTag = objToString.call(object);
+ objTag = getTag(object);
if (objTag == argsTag) {
objTag = objectTag;
} else if (objTag != objectTag) {
}
}
if (!othIsArr) {
- othTag = objToString.call(other);
+ othTag = getTag(other);
if (othTag == argsTag) {
othTag = objectTag;
} else if (othTag != objectTag) {
othIsArr = isTypedArray(other);
}
}
- var objIsObj = objTag == objectTag,
- othIsObj = othTag == objectTag,
+ var objIsObj = objTag == objectTag && !isHostObject(object),
+ othIsObj = othTag == objectTag && !isHostObject(other),
isSameTag = objTag == othTag;
if (isSameTag && !(objIsArr || objIsObj)) {
- return equalByTag(object, other, objTag);
+ return equalByTag(object, other, objTag, equalFunc, customizer, bitmask);
}
- if (!isLoose) {
+ var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
+ if (!isPartial) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
- return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
+ return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, bitmask, stack);
}
}
if (!isSameTag) {
return false;
}
- // Assume cyclic values are equal.
- // For more information on detecting circular references see https://es5.github.io/#JO.
- stackA || (stackA = []);
- stackB || (stackB = []);
-
- var length = stackA.length;
- while (length--) {
- if (stackA[length] == object) {
- return stackB[length] == other;
- }
- }
- // Add `object` and `other` to the stack of traversed objects.
- stackA.push(object);
- stackB.push(other);
-
- var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
-
- stackA.pop();
- stackB.pop();
-
- return result;
+ stack || (stack = new Stack);
+ return (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, bitmask, stack);
}
/**
- * The base implementation of `_.isMatch` without support for callback
- * shorthands and `this` binding.
+ * The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
- * @param {Array} matchData The propery names, values, and compare flags to match.
- * @param {Function} [customizer] The function to customize comparing objects.
+ * @param {Object} source The object of property values to match.
+ * @param {Array} matchData The property names, values, and compare flags to match.
+ * @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
- function baseIsMatch(object, matchData, customizer) {
+ function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
- object = toObject(object);
+ object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
return false;
}
} else {
- var result = customizer ? customizer(objValue, srcValue, key) : undefined;
- if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
+ var stack = new Stack,
+ result = customizer ? customizer(objValue, srcValue, key, object, source, stack) : undefined;
+
+ if (!(result === undefined
+ ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
+ : result
+ )) {
return false;
}
}
}
/**
- * The base implementation of `_.map` without support for callback shorthands
- * and `this` binding.
+ * The base implementation of `_.iteratee`.
+ *
+ * @private
+ * @param {*} [value=_.identity] The value to convert to an iteratee.
+ * @returns {Function} Returns the iteratee.
+ */
+ function baseIteratee(value) {
+ var type = typeof value;
+ if (type == 'function') {
+ return value;
+ }
+ if (value == null) {
+ return identity;
+ }
+ if (type == 'object') {
+ return isArray(value)
+ ? baseMatchesProperty(value[0], value[1])
+ : baseMatches(value);
+ }
+ return property(value);
+ }
+
+ /**
+ * The base implementation of `_.keys` which doesn't skip the constructor
+ * property of prototypes or treat sparse arrays as dense.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
+ function baseKeys(object) {
+ return nativeKeys(Object(object));
+ }
+
+ /**
+ * The base implementation of `_.keysIn` which doesn't skip the constructor
+ * property of prototypes or treat sparse arrays as dense.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
+ function baseKeysIn(object) {
+ object = object == null ? object : Object(object);
+
+ var result = [];
+ for (var key in object) {
+ result.push(key);
+ }
+ return result;
+ }
+
+ // Fallback for IE < 9 with es6-shim.
+ if (enumerate && !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf')) {
+ baseKeysIn = function(object) {
+ return iteratorToArray(enumerate(object));
+ };
+ }
+
+ /**
+ * The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
}
/**
- * The base implementation of `_.matches` which does not clone `source`.
+ * The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
if (object == null) {
return false;
}
- return object[key] === value && (value !== undefined || (key in toObject(object)));
+ return object[key] === value &&
+ (value !== undefined || (key in Object(object)));
};
}
return function(object) {
- return baseIsMatch(object, matchData);
+ return object === source || baseIsMatch(object, source, matchData);
};
}
/**
- * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
+ * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
- * @param {*} srcValue The value to compare.
+ * @param {*} srcValue The value to match.
* @returns {Function} Returns the new function.
*/
function baseMatchesProperty(path, srcValue) {
- var isArr = isArray(path),
- isCommon = isKey(path) && isStrictComparable(srcValue),
- pathKey = (path + '');
-
- path = toPath(path);
return function(object) {
- if (object == null) {
- return false;
- }
- var key = pathKey;
- object = toObject(object);
- if ((isArr || !isCommon) && !(key in object)) {
- object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
- if (object == null) {
- return false;
- }
- key = last(path);
- object = toObject(object);
- }
- return object[key] === srcValue
- ? (srcValue !== undefined || (key in object))
- : baseIsEqual(srcValue, object[key], undefined, true);
+ var objValue = get(object, path);
+ return (objValue === undefined && objValue === srcValue)
+ ? hasIn(object, path)
+ : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
};
}
/**
- * The base implementation of `_.merge` without support for argument juggling,
- * multiple sources, and `this` binding `customizer` functions.
+ * The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
+ * @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
- * @param {Array} [stackA=[]] Tracks traversed source objects.
- * @param {Array} [stackB=[]] Associates values with source counterparts.
- * @returns {Object} Returns `object`.
+ * @param {Object} [stack] Tracks traversed source values and their merged counterparts.
*/
- function baseMerge(object, source, customizer, stackA, stackB) {
- if (!isObject(object)) {
- return object;
+ function baseMerge(object, source, srcIndex, customizer, stack) {
+ if (object === source) {
+ return;
}
- var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
- props = isSrcArr ? undefined : keys(source);
+ var props = (isArray(source) || isTypedArray(source))
+ ? undefined
+ : keysIn(source);
arrayEach(props || source, function(srcValue, key) {
if (props) {
key = srcValue;
srcValue = source[key];
}
- if (isObjectLike(srcValue)) {
- stackA || (stackA = []);
- stackB || (stackB = []);
- baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
+ if (isObject(srcValue)) {
+ stack || (stack = new Stack);
+ baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
- var value = object[key],
- result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
- isCommon = result === undefined;
+ var newValue = customizer
+ ? customizer(object[key], srcValue, (key + ''), object, source, stack)
+ : undefined;
- if (isCommon) {
- result = srcValue;
- }
- if ((result !== undefined || (isSrcArr && !(key in object))) &&
- (isCommon || (result === result ? (result !== value) : (value === value)))) {
- object[key] = result;
+ if (newValue === undefined) {
+ newValue = srcValue;
}
+ assignMergeValue(object, key, newValue);
}
});
- return object;
}
/**
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
+ * @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
- * @param {Function} [customizer] The function to customize merged values.
- * @param {Array} [stackA=[]] Tracks traversed source objects.
- * @param {Array} [stackB=[]] Associates values with source counterparts.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ * @param {Function} [customizer] The function to customize assigned values.
+ * @param {Object} [stack] Tracks traversed source values and their merged counterparts.
*/
- function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
- var length = stackA.length,
- srcValue = source[key];
+ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
+ var objValue = object[key],
+ srcValue = source[key],
+ stacked = stack.get(srcValue);
- while (length--) {
- if (stackA[length] == srcValue) {
- object[key] = stackB[length];
- return;
- }
+ if (stacked) {
+ assignMergeValue(object, key, stacked);
+ return;
}
- var value = object[key],
- result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
- isCommon = result === undefined;
+ var newValue = customizer
+ ? customizer(objValue, srcValue, (key + ''), object, source, stack)
+ : undefined;
+
+ var isCommon = newValue === undefined;
if (isCommon) {
- result = srcValue;
- if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
- result = isArray(value)
- ? value
- : (isArrayLike(value) ? arrayCopy(value) : []);
+ newValue = srcValue;
+ if (isArray(srcValue) || isTypedArray(srcValue)) {
+ if (isArray(objValue)) {
+ newValue = objValue;
+ }
+ else if (isArrayLikeObject(objValue)) {
+ newValue = copyArray(objValue);
+ }
+ else {
+ isCommon = false;
+ newValue = baseClone(srcValue, true);
+ }
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
- result = isArguments(value)
- ? toPlainObject(value)
- : (isPlainObject(value) ? value : {});
+ if (isArguments(objValue)) {
+ newValue = toPlainObject(objValue);
+ }
+ else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
+ isCommon = false;
+ newValue = baseClone(srcValue, true);
+ }
+ else {
+ newValue = objValue;
+ }
}
else {
isCommon = false;
}
}
- // Add the source value to the stack of traversed objects and associate
- // it with its merged value.
- stackA.push(srcValue);
- stackB.push(result);
+ stack.set(srcValue, newValue);
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
- object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
- } else if (result === result ? (result !== value) : (value === value)) {
- object[key] = result;
+ mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
}
+ assignMergeValue(object, key, newValue);
+ }
+
+ /**
+ * The base implementation of `_.orderBy` without param guards.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
+ * @param {string[]} orders The sort orders of `iteratees`.
+ * @returns {Array} Returns the new sorted array.
+ */
+ function baseOrderBy(collection, iteratees, orders) {
+ var index = -1,
+ toIteratee = getIteratee();
+
+ iteratees = arrayMap(iteratees.length ? iteratees : Array(1), function(iteratee) {
+ return toIteratee(iteratee);
+ });
+
+ var result = baseMap(collection, function(value, key, collection) {
+ var criteria = arrayMap(iteratees, function(iteratee) {
+ return iteratee(value);
+ });
+ return { 'criteria': criteria, 'index': ++index, 'value': value };
+ });
+
+ return baseSortBy(result, function(object, other) {
+ return compareMultiple(object, other, orders);
+ });
+ }
+
+ /**
+ * The base implementation of `_.pick` without support for individual
+ * property names.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {string[]} props The property names to pick.
+ * @returns {Object} Returns the new object.
+ */
+ function basePick(object, props) {
+ object = Object(object);
+ return arrayReduce(props, function(result, key) {
+ if (key in object) {
+ result[key] = object[key];
+ }
+ return result;
+ }, {});
+ }
+
+ /**
+ * The base implementation of `_.pickBy` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {Function} predicate The function invoked per property.
+ * @returns {Object} Returns the new object.
+ */
+ function basePickBy(object, predicate) {
+ var result = {};
+ baseForIn(object, function(value, key) {
+ if (predicate(value, key)) {
+ result[key] = value;
+ }
+ });
+ return result;
}
/**
* @returns {Function} Returns the new function.
*/
function basePropertyDeep(path) {
- var pathKey = (path + '');
- path = toPath(path);
return function(object) {
- return baseGet(object, path, pathKey);
+ return baseGet(object, path);
};
}
/**
+ * The base implementation of `_.pullAll`.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to remove.
+ * @returns {Array} Returns `array`.
+ */
+ function basePullAll(array, values) {
+ return basePullAllBy(array, values);
+ }
+
+ /**
+ * The base implementation of `_.pullAllBy` without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to remove.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @returns {Array} Returns `array`.
+ */
+ function basePullAllBy(array, values, iteratee) {
+ var index = -1,
+ length = values.length,
+ seen = array;
+
+ if (iteratee) {
+ seen = arrayMap(array, function(value) { return iteratee(value); });
+ }
+ while (++index < length) {
+ var fromIndex = 0,
+ value = values[index],
+ computed = iteratee ? iteratee(value) : value;
+
+ while ((fromIndex = baseIndexOf(seen, computed, fromIndex)) > -1) {
+ if (seen !== array) {
+ splice.call(seen, fromIndex, 1);
+ }
+ splice.call(array, fromIndex, 1);
+ }
+ }
+ return array;
+ }
+
+ /**
* The base implementation of `_.pullAt` without support for individual
- * index arguments and capturing the removed elements.
+ * indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
*/
function basePullAt(array, indexes) {
- var length = array ? indexes.length : 0;
+ var length = array ? indexes.length : 0,
+ lastIndex = length - 1;
+
while (length--) {
var index = indexes[length];
- if (index != previous && isIndex(index)) {
+ if (lastIndex == length || index != previous) {
var previous = index;
- splice.call(array, index, 1);
+ if (isIndex(index)) {
+ splice.call(array, index, 1);
+ }
+ else if (!isKey(index, array)) {
+ var path = baseCastPath(index),
+ object = parent(array, path);
+
+ if (object != null) {
+ delete object[last(path)];
+ }
+ }
+ else {
+ delete array[index];
+ }
}
}
return array;
}
/**
- * The base implementation of `_.random` without support for argument juggling
- * and returning floating-point numbers.
+ * The base implementation of `_.random` without support for returning
+ * floating-point numbers.
*
* @private
- * @param {number} min The minimum possible value.
- * @param {number} max The maximum possible value.
+ * @param {number} lower The lower bound.
+ * @param {number} upper The upper bound.
* @returns {number} Returns the random number.
*/
- function baseRandom(min, max) {
- return min + nativeFloor(nativeRandom() * (max - min + 1));
+ function baseRandom(lower, upper) {
+ return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
/**
- * The base implementation of `_.reduce` and `_.reduceRight` without support
- * for callback shorthands and `this` binding, which iterates over `collection`
- * using the provided `eachFunc`.
+ * The base implementation of `_.range` and `_.rangeRight` which doesn't
+ * coerce arguments to numbers.
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {*} accumulator The initial value.
- * @param {boolean} initFromCollection Specify using the first or last element
- * of `collection` as the initial value.
- * @param {Function} eachFunc The function to iterate over `collection`.
- * @returns {*} Returns the accumulated value.
+ * @param {number} start The start of the range.
+ * @param {number} end The end of the range.
+ * @param {number} step The value to increment or decrement by.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Array} Returns the new array of numbers.
*/
- function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
- eachFunc(collection, function(value, index, collection) {
- accumulator = initFromCollection
- ? (initFromCollection = false, value)
- : iteratee(accumulator, value, index, collection);
- });
- return accumulator;
+ function baseRange(start, end, step, fromRight) {
+ var index = -1,
+ length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
+ result = Array(length);
+
+ while (length--) {
+ result[fromRight ? length : ++index] = start;
+ start += step;
+ }
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.set`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to set.
+ * @param {*} value The value to set.
+ * @param {Function} [customizer] The function to customize path creation.
+ * @returns {Object} Returns `object`.
+ */
+ function baseSet(object, path, value, customizer) {
+ path = isKey(path, object) ? [path + ''] : baseCastPath(path);
+
+ var index = -1,
+ length = path.length,
+ lastIndex = length - 1,
+ nested = object;
+
+ while (nested != null && ++index < length) {
+ var key = path[index];
+ if (isObject(nested)) {
+ var newValue = value;
+ if (index != lastIndex) {
+ var objValue = nested[key];
+ newValue = customizer ? customizer(objValue, key, nested) : undefined;
+ if (newValue === undefined) {
+ newValue = objValue == null
+ ? (isIndex(path[index + 1]) ? [] : {})
+ : objValue;
+ }
+ }
+ assignValue(nested, key, newValue);
+ }
+ nested = nested[key];
+ }
+ return object;
}
/**
var index = -1,
length = array.length;
- start = start == null ? 0 : (+start || 0);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
- end = (end === undefined || end > length) ? length : (+end || 0);
+ end = end > length ? length : end;
if (end < 0) {
end += length;
}
}
/**
- * The base implementation of `_.some` without support for callback shorthands
- * and `this` binding.
+ * The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if any element passes the predicate check,
- * else `false`.
+ * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`.
*/
function baseSome(collection, predicate) {
var result;
}
/**
- * The base implementation of `_.sortBy` which uses `comparer` to define
- * the sort order of `array` and replaces criteria objects with their
- * corresponding values.
+ * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
+ * performs a binary search of `array` to determine the index at which `value`
+ * should be inserted into `array` in order to maintain its sort order.
*
* @private
- * @param {Array} array The array to sort.
- * @param {Function} comparer The function to define sort order.
- * @returns {Array} Returns `array`.
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {boolean} [retHighest] Specify returning the highest qualified index.
+ * @returns {number} Returns the index at which `value` should be inserted
+ * into `array`.
*/
- function baseSortBy(array, comparer) {
- var length = array.length;
+ function baseSortedIndex(array, value, retHighest) {
+ var low = 0,
+ high = array ? array.length : low;
- array.sort(comparer);
- while (length--) {
- array[length] = array[length].value;
+ if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
+ while (low < high) {
+ var mid = (low + high) >>> 1,
+ computed = array[mid];
+
+ if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
+ low = mid + 1;
+ } else {
+ high = mid;
+ }
+ }
+ return high;
}
- return array;
+ return baseSortedIndexBy(array, value, identity, retHighest);
}
/**
- * The base implementation of `_.sortByOrder` without param guards.
+ * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
+ * which invokes `iteratee` for `value` and each element of `array` to compute
+ * their sort ranking. The iteratee is invoked with one argument; (value).
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
- * @param {boolean[]} orders The sort orders of `iteratees`.
- * @returns {Array} Returns the new sorted array.
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {Function} iteratee The iteratee invoked per element.
+ * @param {boolean} [retHighest] Specify returning the highest qualified index.
+ * @returns {number} Returns the index at which `value` should be inserted into `array`.
*/
- function baseSortByOrder(collection, iteratees, orders) {
- var callback = getCallback(),
- index = -1;
+ function baseSortedIndexBy(array, value, iteratee, retHighest) {
+ value = iteratee(value);
- iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); });
+ var low = 0,
+ high = array ? array.length : 0,
+ valIsNaN = value !== value,
+ valIsNull = value === null,
+ valIsUndef = value === undefined;
- var result = baseMap(collection, function(value) {
- var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); });
- return { 'criteria': criteria, 'index': ++index, 'value': value };
- });
+ while (low < high) {
+ var mid = nativeFloor((low + high) / 2),
+ computed = iteratee(array[mid]),
+ isDef = computed !== undefined,
+ isReflexive = computed === computed;
- return baseSortBy(result, function(object, other) {
- return compareMultiple(object, other, orders);
- });
+ if (valIsNaN) {
+ var setLow = isReflexive || retHighest;
+ } else if (valIsNull) {
+ setLow = isReflexive && isDef && (retHighest || computed != null);
+ } else if (valIsUndef) {
+ setLow = isReflexive && (retHighest || isDef);
+ } else if (computed == null) {
+ setLow = false;
+ } else {
+ setLow = retHighest ? (computed <= value) : (computed < value);
+ }
+ if (setLow) {
+ low = mid + 1;
+ } else {
+ high = mid;
+ }
+ }
+ return nativeMin(high, MAX_ARRAY_INDEX);
}
/**
- * The base implementation of `_.sum` without support for callback shorthands
- * and `this` binding.
+ * The base implementation of `_.sortedUniq`.
*
* @private
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {number} Returns the sum.
+ * @param {Array} array The array to inspect.
+ * @returns {Array} Returns the new duplicate free array.
*/
- function baseSum(collection, iteratee) {
- var result = 0;
- baseEach(collection, function(value, index, collection) {
- result += +iteratee(value, index, collection) || 0;
- });
+ function baseSortedUniq(array) {
+ return baseSortedUniqBy(array);
+ }
+
+ /**
+ * The base implementation of `_.sortedUniqBy` without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @returns {Array} Returns the new duplicate free array.
+ */
+ function baseSortedUniqBy(array, iteratee) {
+ var index = 0,
+ length = array.length,
+ value = array[0],
+ computed = iteratee ? iteratee(value) : value,
+ seen = computed,
+ resIndex = 0,
+ result = [value];
+
+ while (++index < length) {
+ value = array[index],
+ computed = iteratee ? iteratee(value) : value;
+
+ if (!eq(computed, seen)) {
+ seen = computed;
+ result[++resIndex] = value;
+ }
+ }
return result;
}
/**
- * The base implementation of `_.uniq` without support for callback shorthands
- * and `this` binding.
+ * The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
- * @param {Function} [iteratee] The function invoked per iteration.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
- function baseUniq(array, iteratee) {
+ function baseUniq(array, iteratee, comparator) {
var index = -1,
- indexOf = getIndexOf(),
+ includes = arrayIncludes,
length = array.length,
- isCommon = indexOf === baseIndexOf,
- isLarge = isCommon && length >= LARGE_ARRAY_SIZE,
- seen = isLarge ? createCache() : null,
- result = [];
+ isCommon = true,
+ result = [],
+ seen = result;
- if (seen) {
- indexOf = cacheIndexOf;
+ if (comparator) {
isCommon = false;
- } else {
- isLarge = false;
+ includes = arrayIncludesWith;
+ }
+ else if (length >= LARGE_ARRAY_SIZE) {
+ var set = iteratee ? null : createSet(array);
+ if (set) {
+ return setToArray(set);
+ }
+ isCommon = false;
+ includes = cacheHas;
+ seen = new SetCache;
+ }
+ else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
- computed = iteratee ? iteratee(value, index, array) : value;
+ computed = iteratee ? iteratee(value) : value;
- if (isCommon && value === value) {
+ if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
}
result.push(value);
}
- else if (indexOf(seen, computed, 0) < 0) {
- if (iteratee || isLarge) {
+ else if (!includes(seen, computed, comparator)) {
+ if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
/**
- * The base implementation of `_.values` and `_.valuesIn` which creates an
- * array of `object` property values corresponding to the property names
- * of `props`.
+ * The base implementation of `_.unset`.
*
* @private
- * @param {Object} object The object to query.
- * @param {Array} props The property names to get values for.
- * @returns {Object} Returns the array of property values.
+ * @param {Object} object The object to modify.
+ * @param {Array|string} path The path of the property to unset.
+ * @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
- function baseValues(object, props) {
- var index = -1,
- length = props.length,
- result = Array(length);
-
- while (++index < length) {
- result[index] = object[props[index]];
- }
- return result;
+ function baseUnset(object, path) {
+ path = isKey(path, object) ? [path + ''] : baseCastPath(path);
+ object = parent(object, path);
+ var key = last(path);
+ return (object != null && has(object, key)) ? delete object[key] : true;
}
/**
- * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
- * and `_.takeWhile` without support for callback shorthands and `this` binding.
+ * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
+ * without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to query.
var length = array.length,
index = fromRight ? length : -1;
- while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
+ while ((fromRight ? index-- : ++index < length) &&
+ predicate(array[index], index, array)) {}
+
return isDrop
? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
: baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
*
* @private
* @param {*} value The unwrapped value.
- * @param {Array} actions Actions to peform to resolve the unwrapped value.
+ * @param {Array} actions Actions to perform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
*/
function baseWrapperValue(value, actions) {
if (result instanceof LazyWrapper) {
result = result.value();
}
+ return arrayReduce(actions, function(result, action) {
+ return action.func.apply(action.thisArg, arrayPush([result], action.args));
+ }, result);
+ }
+
+ /**
+ * The base implementation of methods like `_.xor`, without support for
+ * iteratee shorthands, that accepts an array of arrays to inspect.
+ *
+ * @private
+ * @param {Array} arrays The arrays to inspect.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of values.
+ */
+ function baseXor(arrays, iteratee, comparator) {
var index = -1,
- length = actions.length;
+ length = arrays.length;
while (++index < length) {
- var action = actions[index];
- result = action.func.apply(action.thisArg, arrayPush([result], action.args));
+ var result = result
+ ? arrayPush(
+ baseDifference(result, arrays[index], iteratee, comparator),
+ baseDifference(arrays[index], result, iteratee, comparator)
+ )
+ : arrays[index];
}
- return result;
+ return (result && result.length) ? baseUniq(result, iteratee, comparator) : [];
}
/**
- * Performs a binary search of `array` to determine the index at which `value`
- * should be inserted into `array` in order to maintain its sort order.
+ * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
*
* @private
- * @param {Array} array The sorted array to inspect.
- * @param {*} value The value to evaluate.
- * @param {boolean} [retHighest] Specify returning the highest qualified index.
- * @returns {number} Returns the index at which `value` should be inserted
- * into `array`.
+ * @param {Array} props The property names.
+ * @param {Array} values The property values.
+ * @param {Function} assignFunc The function to assign values.
+ * @returns {Object} Returns the new object.
*/
- function binaryIndex(array, value, retHighest) {
- var low = 0,
- high = array ? array.length : low;
-
- if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
- while (low < high) {
- var mid = (low + high) >>> 1,
- computed = array[mid];
+ function baseZipObject(props, values, assignFunc) {
+ var index = -1,
+ length = props.length,
+ valsLength = values.length,
+ result = {};
- if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
- low = mid + 1;
- } else {
- high = mid;
- }
- }
- return high;
+ while (++index < length) {
+ assignFunc(result, props[index], index < valsLength ? values[index] : undefined);
}
- return binaryIndexBy(array, value, identity, retHighest);
+ return result;
}
/**
- * This function is like `binaryIndex` except that it invokes `iteratee` for
- * `value` and each element of `array` to compute their sort ranking. The
- * iteratee is invoked with one argument; (value).
+ * Creates a clone of `buffer`.
*
* @private
- * @param {Array} array The sorted array to inspect.
- * @param {*} value The value to evaluate.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {boolean} [retHighest] Specify returning the highest qualified index.
- * @returns {number} Returns the index at which `value` should be inserted
- * into `array`.
+ * @param {Buffer} buffer The buffer to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @returns {Buffer} Returns the cloned buffer.
*/
- function binaryIndexBy(array, value, iteratee, retHighest) {
- value = iteratee(value);
+ function cloneBuffer(buffer, isDeep) {
+ if (isDeep) {
+ return buffer.slice();
+ }
+ var Ctor = buffer.constructor,
+ result = new Ctor(buffer.length);
- var low = 0,
- high = array ? array.length : 0,
- valIsNaN = value !== value,
- valIsNull = value === null,
- valIsUndef = value === undefined;
+ buffer.copy(result);
+ return result;
+ }
- while (low < high) {
- var mid = nativeFloor((low + high) / 2),
- computed = iteratee(array[mid]),
- isDef = computed !== undefined,
- isReflexive = computed === computed;
+ /**
+ * Creates a clone of `arrayBuffer`.
+ *
+ * @private
+ * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
+ * @returns {ArrayBuffer} Returns the cloned array buffer.
+ */
+ function cloneArrayBuffer(arrayBuffer) {
+ var Ctor = arrayBuffer.constructor,
+ result = new Ctor(arrayBuffer.byteLength),
+ view = new Uint8Array(result);
- if (valIsNaN) {
- var setLow = isReflexive || retHighest;
- } else if (valIsNull) {
- setLow = isReflexive && isDef && (retHighest || computed != null);
- } else if (valIsUndef) {
- setLow = isReflexive && (retHighest || isDef);
- } else if (computed == null) {
- setLow = false;
- } else {
- setLow = retHighest ? (computed <= value) : (computed < value);
- }
- if (setLow) {
- low = mid + 1;
- } else {
- high = mid;
- }
- }
- return nativeMin(high, MAX_ARRAY_INDEX);
+ view.set(new Uint8Array(arrayBuffer));
+ return result;
}
/**
- * A specialized version of `baseCallback` which only supports `this` binding
- * and specifying the number of arguments to provide to `func`.
+ * Creates a clone of `map`.
*
* @private
- * @param {Function} func The function to bind.
- * @param {*} thisArg The `this` binding of `func`.
- * @param {number} [argCount] The number of arguments to provide to `func`.
- * @returns {Function} Returns the callback.
+ * @param {Object} map The map to clone.
+ * @returns {Object} Returns the cloned map.
*/
- function bindCallback(func, thisArg, argCount) {
- if (typeof func != 'function') {
- return identity;
- }
- if (thisArg === undefined) {
- return func;
- }
- switch (argCount) {
- case 1: return function(value) {
- return func.call(thisArg, value);
- };
- case 3: return function(value, index, collection) {
- return func.call(thisArg, value, index, collection);
- };
- case 4: return function(accumulator, value, index, collection) {
- return func.call(thisArg, accumulator, value, index, collection);
- };
- case 5: return function(value, other, key, object, source) {
- return func.call(thisArg, value, other, key, object, source);
- };
- }
- return function() {
- return func.apply(thisArg, arguments);
- };
+ function cloneMap(map) {
+ var Ctor = map.constructor;
+ return arrayReduce(mapToArray(map), addMapEntry, new Ctor);
}
/**
- * Creates a clone of the given array buffer.
+ * Creates a clone of `regexp`.
*
* @private
- * @param {ArrayBuffer} buffer The array buffer to clone.
- * @returns {ArrayBuffer} Returns the cloned array buffer.
+ * @param {Object} regexp The regexp to clone.
+ * @returns {Object} Returns the cloned regexp.
*/
- function bufferClone(buffer) {
- var result = new ArrayBuffer(buffer.byteLength),
- view = new Uint8Array(result);
+ function cloneRegExp(regexp) {
+ var Ctor = regexp.constructor,
+ result = new Ctor(regexp.source, reFlags.exec(regexp));
- view.set(new Uint8Array(buffer));
+ result.lastIndex = regexp.lastIndex;
return result;
}
/**
+ * Creates a clone of `set`.
+ *
+ * @private
+ * @param {Object} set The set to clone.
+ * @returns {Object} Returns the cloned set.
+ */
+ function cloneSet(set) {
+ var Ctor = set.constructor;
+ return arrayReduce(setToArray(set), addSetEntry, new Ctor);
+ }
+
+ /**
+ * Creates a clone of the `symbol` object.
+ *
+ * @private
+ * @param {Object} symbol The symbol object to clone.
+ * @returns {Object} Returns the cloned symbol object.
+ */
+ function cloneSymbol(symbol) {
+ return Symbol ? Object(symbolValueOf.call(symbol)) : {};
+ }
+
+ /**
+ * Creates a clone of `typedArray`.
+ *
+ * @private
+ * @param {Object} typedArray The typed array to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @returns {Object} Returns the cloned typed array.
+ */
+ function cloneTypedArray(typedArray, isDeep) {
+ var arrayBuffer = typedArray.buffer,
+ buffer = isDeep ? cloneArrayBuffer(arrayBuffer) : arrayBuffer,
+ Ctor = typedArray.constructor;
+
+ return new Ctor(buffer, typedArray.byteOffset, typedArray.length);
+ }
+
+ /**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @param {Array|Object} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
+ * @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
- function composeArgs(args, partials, holders) {
- var holdersLength = holders.length,
- argsIndex = -1,
- argsLength = nativeMax(args.length - holdersLength, 0),
+ function composeArgs(args, partials, holders, isCurried) {
+ var argsIndex = -1,
+ argsLength = args.length,
+ holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
- result = Array(leftLength + argsLength);
+ rangeLength = nativeMax(argsLength - holdersLength, 0),
+ result = Array(leftLength + rangeLength),
+ isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
- result[holders[argsIndex]] = args[argsIndex];
+ if (isUncurried || argsIndex < argsLength) {
+ result[holders[argsIndex]] = args[argsIndex];
+ }
}
- while (argsLength--) {
+ while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
* @param {Array|Object} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
+ * @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
- function composeArgsRight(args, partials, holders) {
- var holdersIndex = -1,
+ function composeArgsRight(args, partials, holders, isCurried) {
+ var argsIndex = -1,
+ argsLength = args.length,
+ holdersIndex = -1,
holdersLength = holders.length,
- argsIndex = -1,
- argsLength = nativeMax(args.length - holdersLength, 0),
rightIndex = -1,
rightLength = partials.length,
- result = Array(argsLength + rightLength);
+ rangeLength = nativeMax(argsLength - holdersLength, 0),
+ result = Array(rangeLength + rightLength),
+ isUncurried = !isCurried;
- while (++argsIndex < argsLength) {
+ while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
- result[offset + holders[holdersIndex]] = args[argsIndex++];
+ if (isUncurried || argsIndex < argsLength) {
+ result[offset + holders[holdersIndex]] = args[argsIndex++];
+ }
}
return result;
}
/**
- * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
+ * Copies the values of `source` to `array`.
+ *
+ * @private
+ * @param {Array} source The array to copy values from.
+ * @param {Array} [array=[]] The array to copy values to.
+ * @returns {Array} Returns `array`.
+ */
+ function copyArray(source, array) {
+ var index = -1,
+ length = source.length;
+
+ array || (array = Array(length));
+ while (++index < length) {
+ array[index] = source[index];
+ }
+ return array;
+ }
+
+ /**
+ * Copies properties of `source` to `object`.
+ *
+ * @private
+ * @param {Object} source The object to copy properties from.
+ * @param {Array} props The property names to copy.
+ * @param {Object} [object={}] The object to copy properties to.
+ * @returns {Object} Returns `object`.
+ */
+ function copyObject(source, props, object) {
+ return copyObjectWith(source, props, object);
+ }
+
+ /**
+ * This function is like `copyObject` except that it accepts a function to
+ * customize copied values.
*
* @private
- * @param {Function} setter The function to set keys and values of the accumulator object.
- * @param {Function} [initializer] The function to initialize the accumulator object.
+ * @param {Object} source The object to copy properties from.
+ * @param {Array} props The property names to copy.
+ * @param {Object} [object={}] The object to copy properties to.
+ * @param {Function} [customizer] The function to customize copied values.
+ * @returns {Object} Returns `object`.
+ */
+ function copyObjectWith(source, props, object, customizer) {
+ object || (object = {});
+
+ var index = -1,
+ length = props.length;
+
+ while (++index < length) {
+ var key = props[index];
+
+ var newValue = customizer
+ ? customizer(object[key], source[key], key, object, source)
+ : source[key];
+
+ assignValue(object, key, newValue);
+ }
+ return object;
+ }
+
+ /**
+ * Copies own symbol properties of `source` to `object`.
+ *
+ * @private
+ * @param {Object} source The object to copy symbols from.
+ * @param {Object} [object={}] The object to copy symbols to.
+ * @returns {Object} Returns `object`.
+ */
+ function copySymbols(source, object) {
+ return copyObject(source, getSymbols(source), object);
+ }
+
+ /**
+ * Creates a function like `_.groupBy`.
+ *
+ * @private
+ * @param {Function} setter The function to set accumulator values.
+ * @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
- return function(collection, iteratee, thisArg) {
- var result = initializer ? initializer() : {};
- iteratee = getCallback(iteratee, thisArg, 3);
-
- if (isArray(collection)) {
- var index = -1,
- length = collection.length;
+ return function(collection, iteratee) {
+ var func = isArray(collection) ? arrayAggregator : baseAggregator,
+ accumulator = initializer ? initializer() : {};
- while (++index < length) {
- var value = collection[index];
- setter(result, value, iteratee(value, index, collection), collection);
- }
- } else {
- baseEach(collection, function(value, key, collection) {
- setter(result, value, iteratee(value, key, collection), collection);
- });
- }
- return result;
+ return func(collection, setter, getIteratee(iteratee), accumulator);
};
}
/**
- * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
+ * Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
- return restParam(function(object, sources) {
+ return rest(function(object, sources) {
var index = -1,
- length = object == null ? 0 : sources.length,
- customizer = length > 2 ? sources[length - 2] : undefined,
- guard = length > 2 ? sources[2] : undefined,
- thisArg = length > 1 ? sources[length - 1] : undefined;
-
- if (typeof customizer == 'function') {
- customizer = bindCallback(customizer, thisArg, 5);
- length -= 2;
- } else {
- customizer = typeof thisArg == 'function' ? thisArg : undefined;
- length -= (customizer ? 1 : 0);
- }
+ length = sources.length,
+ customizer = length > 1 ? sources[length - 1] : undefined,
+ guard = length > 2 ? sources[2] : undefined;
+
+ customizer = typeof customizer == 'function'
+ ? (length--, customizer)
+ : undefined;
+
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
+ object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
- assigner(object, source, customizer);
+ assigner(object, source, index, customizer);
}
}
return object;
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
- var length = collection ? getLength(collection) : 0;
- if (!isLength(length)) {
+ if (collection == null) {
+ return collection;
+ }
+ if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
- var index = fromRight ? length : -1,
- iterable = toObject(collection);
+ var length = collection.length,
+ index = fromRight ? length : -1,
+ iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
}
/**
- * Creates a base function for `_.forIn` or `_.forInRight`.
+ * Creates a base function for methods like `_.forIn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
- var iterable = toObject(object),
+ var index = -1,
+ iterable = Object(object),
props = keysFunc(object),
- length = props.length,
- index = fromRight ? length : -1;
+ length = props.length;
- while ((fromRight ? index-- : ++index < length)) {
- var key = props[index];
+ while (length--) {
+ var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
/**
- * Creates a function that wraps `func` and invokes it with the `this`
+ * Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
- * @param {Function} func The function to bind.
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
- * @returns {Function} Returns the new bound function.
+ * @returns {Function} Returns the new wrapped function.
*/
- function createBindWrapper(func, thisArg) {
- var Ctor = createCtorWrapper(func);
+ function createBaseWrapper(func, bitmask, thisArg) {
+ var isBind = bitmask & BIND_FLAG,
+ Ctor = createCtorWrapper(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
- return fn.apply(thisArg, arguments);
+ return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
/**
- * Creates a `Set` cache object to optimize linear searches of large arrays.
+ * Creates a function like `_.lowerFirst`.
*
* @private
- * @param {Array} [values] The values to cache.
- * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
+ * @param {string} methodName The name of the `String` case method to use.
+ * @returns {Function} Returns the new function.
*/
- function createCache(values) {
- return (nativeCreate && Set) ? new SetCache(values) : null;
+ function createCaseFirst(methodName) {
+ return function(string) {
+ string = toString(string);
+
+ var strSymbols = reHasComplexSymbol.test(string)
+ ? stringToArray(string)
+ : undefined;
+
+ var chr = strSymbols ? strSymbols[0] : string.charAt(0),
+ trailing = strSymbols ? strSymbols.slice(1).join('') : string.slice(1);
+
+ return chr[methodName]() + trailing;
+ };
}
/**
- * Creates a function that produces compound words out of the words in a
- * given string.
+ * Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
*/
function createCompounder(callback) {
return function(string) {
- var index = -1,
- array = words(deburr(string)),
- length = array.length,
- result = '';
-
- while (++index < length) {
- result = callback(result, array[index], index);
- }
- return result;
+ return arrayReduce(words(deburr(string)), callback, '');
};
}
}
/**
- * Creates a `_.curry` or `_.curryRight` function.
- *
- * @private
- * @param {boolean} flag The curry bit flag.
- * @returns {Function} Returns the new curry function.
- */
- function createCurry(flag) {
- function curryFunc(func, arity, guard) {
- if (guard && isIterateeCall(func, arity, guard)) {
- arity = undefined;
- }
- var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity);
- result.placeholder = curryFunc.placeholder;
- return result;
- }
- return curryFunc;
- }
-
- /**
- * Creates a `_.defaults` or `_.defaultsDeep` function.
+ * Creates a function that wraps `func` to enable currying.
*
* @private
- * @param {Function} assigner The function to assign values.
- * @param {Function} customizer The function to customize assigned values.
- * @returns {Function} Returns the new defaults function.
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
+ * @param {number} arity The arity of `func`.
+ * @returns {Function} Returns the new wrapped function.
*/
- function createDefaults(assigner, customizer) {
- return restParam(function(args) {
- var object = args[0];
- if (object == null) {
- return object;
- }
- args.push(customizer);
- return assigner.apply(undefined, args);
- });
- }
+ function createCurryWrapper(func, bitmask, arity) {
+ var Ctor = createCtorWrapper(func);
- /**
- * Creates a `_.max` or `_.min` function.
- *
- * @private
- * @param {Function} comparator The function used to compare values.
- * @param {*} exValue The initial extremum value.
- * @returns {Function} Returns the new extremum function.
- */
- function createExtremum(comparator, exValue) {
- return function(collection, iteratee, thisArg) {
- if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
- iteratee = undefined;
- }
- iteratee = getCallback(iteratee, thisArg, 3);
- if (iteratee.length == 1) {
- collection = isArray(collection) ? collection : toIterable(collection);
- var result = arrayExtremum(collection, iteratee, comparator, exValue);
- if (!(collection.length && result === exValue)) {
- return result;
- }
- }
- return baseExtremum(collection, iteratee, comparator, exValue);
- };
- }
+ function wrapper() {
+ var length = arguments.length,
+ args = Array(length),
+ index = length,
+ placeholder = getPlaceholder(wrapper);
- /**
- * Creates a `_.find` or `_.findLast` function.
- *
- * @private
- * @param {Function} eachFunc The function to iterate over a collection.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new find function.
- */
- function createFind(eachFunc, fromRight) {
- return function(collection, predicate, thisArg) {
- predicate = getCallback(predicate, thisArg, 3);
- if (isArray(collection)) {
- var index = baseFindIndex(collection, predicate, fromRight);
- return index > -1 ? collection[index] : undefined;
+ while (index--) {
+ args[index] = arguments[index];
}
- return baseFind(collection, predicate, eachFunc);
- };
- }
+ var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
+ ? []
+ : replaceHolders(args, placeholder);
- /**
- * Creates a `_.findIndex` or `_.findLastIndex` function.
- *
- * @private
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new find function.
- */
- function createFindIndex(fromRight) {
- return function(array, predicate, thisArg) {
- if (!(array && array.length)) {
- return -1;
+ length -= holders.length;
+ if (length < arity) {
+ return createRecurryWrapper(
+ func, bitmask, createHybridWrapper, wrapper.placeholder, undefined,
+ args, holders, undefined, undefined, arity - length);
}
- predicate = getCallback(predicate, thisArg, 3);
- return baseFindIndex(array, predicate, fromRight);
- };
- }
-
- /**
- * Creates a `_.findKey` or `_.findLastKey` function.
- *
- * @private
- * @param {Function} objectFunc The function to iterate over an object.
- * @returns {Function} Returns the new find function.
- */
- function createFindKey(objectFunc) {
- return function(object, predicate, thisArg) {
- predicate = getCallback(predicate, thisArg, 3);
- return baseFind(object, predicate, objectFunc, true);
- };
+ var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
+ return apply(fn, this, args);
+ }
+ return wrapper;
}
/**
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
- return function() {
- var wrapper,
- length = arguments.length,
- index = fromRight ? length : -1,
- leftIndex = 0,
- funcs = Array(length);
+ return rest(function(funcs) {
+ funcs = baseFlatten(funcs, 1);
- while ((fromRight ? index-- : ++index < length)) {
- var func = funcs[leftIndex++] = arguments[index];
+ var length = funcs.length,
+ index = length,
+ prereq = LodashWrapper.prototype.thru;
+
+ if (fromRight) {
+ funcs.reverse();
+ }
+ while (index--) {
+ var func = funcs[index];
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
- if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
- wrapper = new LodashWrapper([], true);
+ if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
+ var wrapper = new LodashWrapper([], true);
}
}
- index = wrapper ? -1 : length;
+ index = wrapper ? index : length;
while (++index < length) {
func = funcs[index];
var funcName = getFuncName(func),
data = funcName == 'wrapper' ? getData(func) : undefined;
- if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
+ if (data && isLaziable(data[0]) &&
+ data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) &&
+ !data[4].length && data[9] == 1
+ ) {
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
} else {
wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
var args = arguments,
value = args[0];
- if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
+ if (wrapper && args.length == 1 &&
+ isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
return wrapper.plant(value).value();
}
var index = 0,
}
return result;
};
- };
- }
-
- /**
- * Creates a function for `_.forEach` or `_.forEachRight`.
- *
- * @private
- * @param {Function} arrayFunc The function to iterate over an array.
- * @param {Function} eachFunc The function to iterate over a collection.
- * @returns {Function} Returns the new each function.
- */
- function createForEach(arrayFunc, eachFunc) {
- return function(collection, iteratee, thisArg) {
- return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
- ? arrayFunc(collection, iteratee)
- : eachFunc(collection, bindCallback(iteratee, thisArg, 3));
- };
- }
-
- /**
- * Creates a function for `_.forIn` or `_.forInRight`.
- *
- * @private
- * @param {Function} objectFunc The function to iterate over an object.
- * @returns {Function} Returns the new each function.
- */
- function createForIn(objectFunc) {
- return function(object, iteratee, thisArg) {
- if (typeof iteratee != 'function' || thisArg !== undefined) {
- iteratee = bindCallback(iteratee, thisArg, 3);
- }
- return objectFunc(object, iteratee, keysIn);
- };
- }
-
- /**
- * Creates a function for `_.forOwn` or `_.forOwnRight`.
- *
- * @private
- * @param {Function} objectFunc The function to iterate over an object.
- * @returns {Function} Returns the new each function.
- */
- function createForOwn(objectFunc) {
- return function(object, iteratee, thisArg) {
- if (typeof iteratee != 'function' || thisArg !== undefined) {
- iteratee = bindCallback(iteratee, thisArg, 3);
- }
- return objectFunc(object, iteratee);
- };
- }
-
- /**
- * Creates a function for `_.mapKeys` or `_.mapValues`.
- *
- * @private
- * @param {boolean} [isMapKeys] Specify mapping keys instead of values.
- * @returns {Function} Returns the new map function.
- */
- function createObjectMapper(isMapKeys) {
- return function(object, iteratee, thisArg) {
- var result = {};
- iteratee = getCallback(iteratee, thisArg, 3);
-
- baseForOwn(object, function(value, key, object) {
- var mapped = iteratee(value, key, object);
- key = isMapKeys ? mapped : key;
- value = isMapKeys ? value : mapped;
- result[key] = value;
- });
- return result;
- };
- }
-
- /**
- * Creates a function for `_.padLeft` or `_.padRight`.
- *
- * @private
- * @param {boolean} [fromRight] Specify padding from the right.
- * @returns {Function} Returns the new pad function.
- */
- function createPadDir(fromRight) {
- return function(string, length, chars) {
- string = baseToString(string);
- return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
- };
- }
-
- /**
- * Creates a `_.partial` or `_.partialRight` function.
- *
- * @private
- * @param {boolean} flag The partial bit flag.
- * @returns {Function} Returns the new partial function.
- */
- function createPartial(flag) {
- var partialFunc = restParam(function(func, partials) {
- var holders = replaceHolders(partials, partialFunc.placeholder);
- return createWrapper(func, flag, undefined, partials, holders);
});
- return partialFunc;
}
/**
- * Creates a function for `_.reduce` or `_.reduceRight`.
+ * Creates a function that wraps `func` to invoke it with optional `this`
+ * binding of `thisArg`, partial application, and currying.
*
* @private
- * @param {Function} arrayFunc The function to iterate over an array.
- * @param {Function} eachFunc The function to iterate over a collection.
- * @returns {Function} Returns the new each function.
- */
- function createReduce(arrayFunc, eachFunc) {
- return function(collection, iteratee, accumulator, thisArg) {
- var initFromArray = arguments.length < 3;
- return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
- ? arrayFunc(collection, iteratee, accumulator, initFromArray)
- : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
- };
- }
-
- /**
- * Creates a function that wraps `func` and invokes it with optional `this`
- * binding of, partial application, and currying.
- *
- * @private
- * @param {Function|string} func The function or method name to reference.
- * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
+ * @param {Function|string} func The function or method name to wrap.
+ * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
var isAry = bitmask & ARY_FLAG,
isBind = bitmask & BIND_FLAG,
isBindKey = bitmask & BIND_KEY_FLAG,
- isCurry = bitmask & CURRY_FLAG,
- isCurryBound = bitmask & CURRY_BOUND_FLAG,
- isCurryRight = bitmask & CURRY_RIGHT_FLAG,
+ isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),
+ isFlip = bitmask & FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtorWrapper(func);
function wrapper() {
- // Avoid `arguments` object use disqualifying optimizations by
- // converting it to an array before providing it to other functions.
var length = arguments.length,
index = length,
args = Array(length);
while (index--) {
args[index] = arguments[index];
}
+ if (isCurried) {
+ var placeholder = getPlaceholder(wrapper),
+ holdersCount = countHolders(args, placeholder);
+ }
if (partials) {
- args = composeArgs(args, partials, holders);
+ args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
- args = composeArgsRight(args, partialsRight, holdersRight);
- }
- if (isCurry || isCurryRight) {
- var placeholder = wrapper.placeholder,
- argsHolders = replaceHolders(args, placeholder);
-
- length -= argsHolders.length;
- if (length < arity) {
- var newArgPos = argPos ? arrayCopy(argPos) : undefined,
- newArity = nativeMax(arity - length, 0),
- newsHolders = isCurry ? argsHolders : undefined,
- newHoldersRight = isCurry ? undefined : argsHolders,
- newPartials = isCurry ? args : undefined,
- newPartialsRight = isCurry ? undefined : args;
-
- bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
- bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
-
- if (!isCurryBound) {
- bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
- }
- var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
- result = createHybridWrapper.apply(undefined, newData);
-
- if (isLaziable(func)) {
- setData(result, newData);
- }
- result.placeholder = placeholder;
- return result;
- }
+ args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
+ }
+ length -= holdersCount;
+ if (isCurried && length < arity) {
+ var newHolders = replaceHolders(args, placeholder);
+ return createRecurryWrapper(
+ func, bitmask, createHybridWrapper, wrapper.placeholder, thisArg,
+ args, newHolders, argPos, ary, arity - length
+ );
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
+ length = args.length;
if (argPos) {
args = reorder(args, argPos);
+ } else if (isFlip && length > 1) {
+ args.reverse();
}
- if (isAry && ary < args.length) {
+ if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
- fn = Ctor || createCtorWrapper(func);
+ fn = Ctor || createCtorWrapper(fn);
}
return fn.apply(thisBinding, args);
}
}
/**
- * Creates the padding required for `string` based on the given `length`.
- * The `chars` string is truncated if the number of characters exceeds `length`.
+ * Creates a function like `_.invertBy`.
+ *
+ * @private
+ * @param {Function} setter The function to set accumulator values.
+ * @param {Function} toIteratee The function to resolve iteratees.
+ * @returns {Function} Returns the new inverter function.
+ */
+ function createInverter(setter, toIteratee) {
+ return function(object, iteratee) {
+ return baseInverter(object, setter, toIteratee(iteratee), {});
+ };
+ }
+
+ /**
+ * Creates a function like `_.over`.
+ *
+ * @private
+ * @param {Function} arrayFunc The function to iterate over iteratees.
+ * @returns {Function} Returns the new invoker function.
+ */
+ function createOver(arrayFunc) {
+ return rest(function(iteratees) {
+ iteratees = arrayMap(baseFlatten(iteratees, 1), getIteratee());
+ return rest(function(args) {
+ var thisArg = this;
+ return arrayFunc(iteratees, function(iteratee) {
+ return apply(iteratee, thisArg, args);
+ });
+ });
+ });
+ }
+
+ /**
+ * Creates the padding for `string` based on `length`. The `chars` string
+ * is truncated if the number of characters exceeds `length`.
*
* @private
* @param {string} string The string to create padding for.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
- * @returns {string} Returns the pad for `string`.
+ * @returns {string} Returns the padding for `string`.
*/
function createPadding(string, length, chars) {
- var strLength = string.length;
- length = +length;
+ length = toInteger(length);
- if (strLength >= length || !nativeIsFinite(length)) {
+ var strLength = stringSize(string);
+ if (!length || strLength >= length) {
return '';
}
var padLength = length - strLength;
- chars = chars == null ? ' ' : (chars + '');
- return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
+ chars = chars === undefined ? ' ' : (chars + '');
+
+ var result = repeat(chars, nativeCeil(padLength / stringSize(chars)));
+ return reHasComplexSymbol.test(chars)
+ ? stringToArray(result).slice(0, padLength).join('')
+ : result.slice(0, padLength);
}
/**
- * Creates a function that wraps `func` and invokes it with the optional `this`
+ * Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg` and the `partials` prepended to those provided to
* the wrapper.
*
* @private
- * @param {Function} func The function to partially apply arguments to.
- * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to the new function.
- * @returns {Function} Returns the new bound function.
+ * @returns {Function} Returns the new wrapped function.
*/
function createPartialWrapper(func, bitmask, thisArg, partials) {
var isBind = bitmask & BIND_FLAG,
Ctor = createCtorWrapper(func);
function wrapper() {
- // Avoid `arguments` object use disqualifying optimizations by
- // converting it to an array before providing it `func`.
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
- args = Array(leftLength + argsLength);
+ args = Array(leftLength + argsLength),
+ fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
- var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
- return fn.apply(isBind ? thisArg : this, args);
+ return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
/**
- * Creates a `_.ceil`, `_.floor`, or `_.round` function.
+ * Creates a `_.range` or `_.rangeRight` function.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new range function.
+ */
+ function createRange(fromRight) {
+ return function(start, end, step) {
+ if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
+ end = step = undefined;
+ }
+ // Ensure the sign of `-0` is preserved.
+ start = toNumber(start);
+ start = start === start ? start : 0;
+ if (end === undefined) {
+ end = start;
+ start = 0;
+ } else {
+ end = toNumber(end) || 0;
+ }
+ step = step === undefined ? (start < end ? 1 : -1) : (toNumber(step) || 0);
+ return baseRange(start, end, step, fromRight);
+ };
+ }
+
+ /**
+ * Creates a function that wraps `func` to continue currying.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
+ * @param {Function} wrapFunc The function to create the `func` wrapper.
+ * @param {*} placeholder The placeholder value.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {Array} [partials] The arguments to prepend to those provided to the new function.
+ * @param {Array} [holders] The `partials` placeholder indexes.
+ * @param {Array} [argPos] The argument positions of the new function.
+ * @param {number} [ary] The arity cap of `func`.
+ * @param {number} [arity] The arity of `func`.
+ * @returns {Function} Returns the new wrapped function.
+ */
+ function createRecurryWrapper(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
+ var isCurry = bitmask & CURRY_FLAG,
+ newArgPos = argPos ? copyArray(argPos) : undefined,
+ newHolders = isCurry ? holders : undefined,
+ newHoldersRight = isCurry ? undefined : holders,
+ newPartials = isCurry ? partials : undefined,
+ newPartialsRight = isCurry ? undefined : partials;
+
+ bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
+ bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
+
+ if (!(bitmask & CURRY_BOUND_FLAG)) {
+ bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
+ }
+ var newData = [
+ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
+ newHoldersRight, newArgPos, ary, arity
+ ];
+
+ var result = wrapFunc.apply(undefined, newData);
+ if (isLaziable(func)) {
+ setData(result, newData);
+ }
+ result.placeholder = placeholder;
+ return result;
+ }
+
+ /**
+ * Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
function createRound(methodName) {
var func = Math[methodName];
return function(number, precision) {
- precision = precision === undefined ? 0 : (+precision || 0);
+ number = toNumber(number);
+ precision = toInteger(precision);
if (precision) {
- precision = pow(10, precision);
- return func(number * precision) / precision;
+ // Shift with exponential notation to avoid floating-point issues.
+ // See [MDN](https://mdn.io/round#Examples) for more details.
+ var pair = (toString(number) + 'e').split('e'),
+ value = func(pair[0] + 'e' + (+pair[1] + precision));
+
+ pair = (toString(value) + 'e').split('e');
+ return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
};
}
/**
- * Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
+ * Creates a set of `values`.
*
* @private
- * @param {boolean} [retHighest] Specify returning the highest qualified index.
- * @returns {Function} Returns the new index function.
- */
- function createSortedIndex(retHighest) {
- return function(array, value, iteratee, thisArg) {
- var callback = getCallback(iteratee);
- return (iteratee == null && callback === baseCallback)
- ? binaryIndex(array, value, retHighest)
- : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
- };
- }
+ * @param {Array} values The values to add to the set.
+ * @returns {Object} Returns the new set.
+ */
+ var createSet = !(Set && new Set([1, 2]).size === 2) ? noop : function(values) {
+ return new Set(values);
+ };
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
- * @param {Function|string} func The function or method name to reference.
- * @param {number} bitmask The bitmask of flags.
+ * @param {Function|string} func The function or method name to wrap.
+ * @param {number} bitmask The bitmask of wrapper flags.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
- length -= (holders ? holders.length : 0);
+ ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
+ arity = arity === undefined ? arity : toInteger(arity);
+ length -= holders ? holders.length : 0;
+
if (bitmask & PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
- var data = isBindKey ? undefined : getData(func),
- newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
+ var data = isBindKey ? undefined : getData(func);
+
+ var newData = [
+ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
+ argPos, ary, arity
+ ];
if (data) {
mergeData(newData, data);
- bitmask = newData[1];
- arity = newData[9];
}
- newData[9] = arity == null
+ func = newData[0];
+ bitmask = newData[1];
+ thisArg = newData[2];
+ partials = newData[3];
+ holders = newData[4];
+ arity = newData[9] = newData[9] == null
? (isBindKey ? 0 : func.length)
- : (nativeMax(arity - length, 0) || 0);
+ : nativeMax(newData[9] - length, 0);
- if (bitmask == BIND_FLAG) {
- var result = createBindWrapper(newData[0], newData[2]);
- } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
- result = createPartialWrapper.apply(undefined, newData);
+ if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {
+ bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);
+ }
+ if (!bitmask || bitmask == BIND_FLAG) {
+ var result = createBaseWrapper(func, bitmask, thisArg);
+ } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {
+ result = createCurryWrapper(func, bitmask, arity);
+ } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {
+ result = createPartialWrapper(func, bitmask, thisArg, partials);
} else {
result = createHybridWrapper.apply(undefined, newData);
}
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} [customizer] The function to customize comparing arrays.
- * @param {boolean} [isLoose] Specify performing partial comparisons.
- * @param {Array} [stackA] Tracks traversed `value` objects.
- * @param {Array} [stackB] Tracks traversed `other` objects.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` for more details.
+ * @param {Object} [stack] Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
- function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
+ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
var index = -1,
+ isPartial = bitmask & PARTIAL_COMPARE_FLAG,
+ isUnordered = bitmask & UNORDERED_COMPARE_FLAG,
arrLength = array.length,
othLength = other.length;
- if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
+ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
+ // Assume cyclic values are equal.
+ var stacked = stack.get(array);
+ if (stacked) {
+ return stacked == other;
+ }
+ var result = true;
+ stack.set(array, other);
+
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
- othValue = other[index],
- result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
+ othValue = other[index];
- if (result !== undefined) {
- if (result) {
+ if (customizer) {
+ var compared = isPartial
+ ? customizer(othValue, arrValue, index, other, array, stack)
+ : customizer(arrValue, othValue, index, array, other, stack);
+ }
+ if (compared !== undefined) {
+ if (compared) {
continue;
}
- return false;
+ result = false;
+ break;
}
// Recursively compare arrays (susceptible to call stack limits).
- if (isLoose) {
+ if (isUnordered) {
if (!arraySome(other, function(othValue) {
- return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
+ return arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack);
})) {
- return false;
+ result = false;
+ break;
}
- } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
- return false;
+ } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
+ result = false;
+ break;
}
}
- return true;
+ stack['delete'](array);
+ return result;
}
/**
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` for more details.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
- function equalByTag(object, other, tag) {
+ function equalByTag(object, other, tag, equalFunc, customizer, bitmask) {
switch (tag) {
+ case arrayBufferTag:
+ if ((object.byteLength != other.byteLength) ||
+ !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
+ return false;
+ }
+ return true;
+
case boolTag:
case dateTag:
// Coerce dates and booleans to numbers, dates to milliseconds and booleans
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
- return (object != +object)
- ? other != +other
- : object == +other;
+ return (object != +object) ? other != +other : object == +other;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings primitives and string
// objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
return object == (other + '');
+
+ case mapTag:
+ var convert = mapToArray;
+
+ case setTag:
+ var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
+ convert || (convert = setToArray);
+
+ // Recursively compare objects (susceptible to call stack limits).
+ return (isPartial || object.size == other.size) &&
+ equalFunc(convert(object), convert(other), customizer, bitmask | UNORDERED_COMPARE_FLAG);
+
+ case symbolTag:
+ return !!Symbol && (symbolValueOf.call(object) == symbolValueOf.call(other));
}
return false;
}
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} [customizer] The function to customize comparing values.
- * @param {boolean} [isLoose] Specify performing partial comparisons.
- * @param {Array} [stackA] Tracks traversed `value` objects.
- * @param {Array} [stackB] Tracks traversed `other` objects.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` for more details.
+ * @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
- function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
- var objProps = keys(object),
+ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
+ var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
+ objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
- if (objLength != othLength && !isLoose) {
+ if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
- if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
+ if (!(isPartial ? key in other : baseHas(other, key))) {
return false;
}
}
- var skipCtor = isLoose;
+ // Assume cyclic values are equal.
+ var stacked = stack.get(object);
+ if (stacked) {
+ return stacked == other;
+ }
+ var result = true;
+ stack.set(object, other);
+
+ var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
- othValue = other[key],
- result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
+ othValue = other[key];
+ if (customizer) {
+ var compared = isPartial
+ ? customizer(othValue, objValue, key, other, object, stack)
+ : customizer(objValue, othValue, key, object, other, stack);
+ }
// Recursively compare objects (susceptible to call stack limits).
- if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
- return false;
+ if (!(compared === undefined
+ ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
+ : compared
+ )) {
+ result = false;
+ break;
}
skipCtor || (skipCtor = key == 'constructor');
}
- if (!skipCtor) {
+ if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
- return false;
+ result = false;
}
}
- return true;
- }
-
- /**
- * Gets the appropriate "callback" function. If the `_.callback` method is
- * customized this function returns the custom method, otherwise it returns
- * the `baseCallback` function. If arguments are provided the chosen function
- * is invoked with them and its result is returned.
- *
- * @private
- * @returns {Function} Returns the chosen function or its result.
- */
- function getCallback(func, thisArg, argCount) {
- var result = lodash.callback || callback;
- result = result === callback ? baseCallback : result;
- return argCount ? result(func, thisArg, argCount) : result;
+ stack['delete'](object);
+ return result;
}
/**
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
- length = array ? array.length : 0;
+ length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
}
/**
- * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
+ * Gets the appropriate "iteratee" function. If the `_.iteratee` method is
* customized this function returns the custom method, otherwise it returns
- * the `baseIndexOf` function. If arguments are provided the chosen function
- * is invoked with them and its result is returned.
+ * `baseIteratee`. If arguments are provided the chosen function is invoked
+ * with them and its result is returned.
*
* @private
- * @returns {Function|number} Returns the chosen function or its result.
+ * @param {*} [value] The value to convert to an iteratee.
+ * @param {number} [arity] The arity of the created iteratee.
+ * @returns {Function} Returns the chosen function or its result.
*/
- function getIndexOf(collection, target, fromIndex) {
- var result = lodash.indexOf || indexOf;
- result = result === indexOf ? baseIndexOf : result;
- return collection ? result(collection, target, fromIndex) : result;
+ function getIteratee() {
+ var result = lodash.iteratee || iteratee;
+ result = result === iteratee ? baseIteratee : result;
+ return arguments.length ? result(arguments[0], arguments[1]) : result;
}
/**
var getLength = baseProperty('length');
/**
- * Gets the propery names, values, and compare flags of `object`.
+ * Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
- var result = pairs(object),
+ var result = toPairs(object),
length = result.length;
while (length--) {
}
/**
+ * Gets the argument placeholder value for `func`.
+ *
+ * @private
+ * @param {Function} func The function to inspect.
+ * @returns {*} Returns the placeholder value.
+ */
+ function getPlaceholder(func) {
+ var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
+ return object.placeholder;
+ }
+
+ /**
+ * Creates an array of the own symbol properties of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of symbols.
+ */
+ var getSymbols = getOwnPropertySymbols || function() {
+ return [];
+ };
+
+ /**
+ * Gets the `toStringTag` of `value`.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @returns {string} Returns the `toStringTag`.
+ */
+ function getTag(value) {
+ return objectToString.call(value);
+ }
+
+ // Fallback for IE 11 providing `toStringTag` values for maps, sets, and weakmaps.
+ if ((Map && getTag(new Map) != mapTag) ||
+ (Set && getTag(new Set) != setTag) ||
+ (WeakMap && getTag(new WeakMap) != weakMapTag)) {
+ getTag = function(value) {
+ var result = objectToString.call(value),
+ Ctor = result == objectTag ? value.constructor : null,
+ ctorString = typeof Ctor == 'function' ? funcToString.call(Ctor) : '';
+
+ if (ctorString) {
+ switch (ctorString) {
+ case mapCtorString: return mapTag;
+ case setCtorString: return setTag;
+ case weakMapCtorString: return weakMapTag;
+ }
+ }
+ return result;
+ };
+ }
+
+ /**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
}
/**
+ * Checks if `path` exists on `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @param {Function} hasFunc The function to check properties.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
+ */
+ function hasPath(object, path, hasFunc) {
+ if (object == null) {
+ return false;
+ }
+ var result = hasFunc(object, path);
+ if (!result && !isKey(path)) {
+ path = baseCastPath(path);
+ object = parent(object, path);
+ if (object != null) {
+ path = last(path);
+ result = hasFunc(object, path);
+ }
+ }
+ var length = object ? object.length : undefined;
+ return result || (
+ !!length && isLength(length) && isIndex(path, length) &&
+ (isArray(object) || isString(object) || isArguments(object))
+ );
+ }
+
+ /**
* Initializes an array clone.
*
* @private
*/
function initCloneArray(array) {
var length = array.length,
- result = new array.constructor(length);
+ result = array.constructor(length);
- // Add array properties assigned by `RegExp#exec`.
+ // Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
- var Ctor = object.constructor;
- if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
- Ctor = Object;
- }
- return new Ctor;
+ return (isFunction(object.constructor) && !isPrototype(object))
+ ? baseCreate(getPrototypeOf(object))
+ : {};
}
/**
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
- return bufferClone(object);
+ return cloneArrayBuffer(object);
case boolTag:
case dateTag:
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
- var buffer = object.buffer;
- return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
+ return cloneTypedArray(object, isDeep);
+
+ case mapTag:
+ return cloneMap(object);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
- var result = new Ctor(object.source, reFlags.exec(object));
- result.lastIndex = object.lastIndex;
+ return cloneRegExp(object);
+
+ case setTag:
+ return cloneSet(object);
+
+ case symbolTag:
+ return cloneSymbol(object);
}
- return result;
}
/**
- * Invokes the method at `path` on `object`.
+ * Creates an array of index keys for `object` values of arrays,
+ * `arguments` objects, and strings, otherwise `null` is returned.
*
* @private
* @param {Object} object The object to query.
- * @param {Array|string} path The path of the method to invoke.
- * @param {Array} args The arguments to invoke the method with.
- * @returns {*} Returns the result of the invoked method.
+ * @returns {Array|null} Returns index keys, else `null`.
*/
- function invokePath(object, path, args) {
- if (object != null && !isKey(path, object)) {
- path = toPath(path);
- object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
- path = last(path);
+ function indexKeys(object) {
+ var length = object ? object.length : undefined;
+ if (isLength(length) &&
+ (isArray(object) || isString(object) || isArguments(object))) {
+ return baseTimes(length, String);
}
- var func = object == null ? object : object[path];
- return func == null ? undefined : func.apply(object, args);
- }
-
- /**
- * Checks if `value` is array-like.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
- */
- function isArrayLike(value) {
- return value != null && isLength(getLength(value));
+ return null;
}
/**
- * Checks if `value` is a valid array-like index.
- *
- * @private
- * @param {*} value The value to check.
- * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
- * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
- */
- function isIndex(value, length) {
- value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
- length = length == null ? MAX_SAFE_INTEGER : length;
- return value > -1 && value % 1 == 0 && value < length;
- }
-
- /**
- * Checks if the provided arguments are from an iteratee call.
+ * Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
- var other = object[index];
- return value === value ? (value === other) : (other !== other);
+ return eq(object[index], value);
}
return false;
}
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
- var type = typeof value;
- if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
+ if (typeof value == 'number') {
return true;
}
- if (isArray(value)) {
- return false;
- }
- var result = !reIsDeepProp.test(value);
- return result || (object != null && value in toObject(object));
+ return !isArray(value) &&
+ (reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
+ (object != null && value in Object(object)));
+ }
+
+ /**
+ * Checks if `value` is suitable for use as unique object key.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
+ */
+ function isKeyable(value) {
+ var type = typeof value;
+ return type == 'number' || type == 'boolean' ||
+ (type == 'string' && value != '__proto__') || value == null;
}
/**
}
/**
- * Checks if `value` is a valid array-like length.
- *
- * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
+ * Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
+ * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
- function isLength(value) {
- return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
+ function isPrototype(value) {
+ var Ctor = value && value.constructor,
+ proto = (isFunction(Ctor) && Ctor.prototype) || objectProto;
+
+ return value === proto;
}
/**
/**
* Merges the function metadata of `source` into `data`.
*
- * Merging metadata reduces the number of wrappers required to invoke a function.
+ * Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
- * augment function arguments, making the order in which they are executed important,
+ * modify function arguments, making the order in which they are executed important,
* preventing the merging of metadata. However, we make an exception for a safe
- * common case where curried functions have `_.ary` and or `_.rearg` applied.
+ * combined case where curried functions have `_.ary` and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
- isCommon = newBitmask < ARY_FLAG;
+ isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG);
var isCombo =
- (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
- (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
- (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
+ ((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) ||
+ ((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) ||
+ ((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
if (srcBitmask & BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
- newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
+ newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
- data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
- data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
+ data[3] = partials ? composeArgs(partials, value, source[4]) : copyArray(value);
+ data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : copyArray(source[4]);
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
- data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
- data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
+ data[5] = partials ? composeArgsRight(partials, value, source[6]) : copyArray(value);
+ data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : copyArray(source[6]);
}
// Use source `argPos` if available.
value = source[7];
if (value) {
- data[7] = arrayCopy(value);
+ data[7] = copyArray(value);
}
// Use source `ary` if it's smaller.
if (srcBitmask & ARY_FLAG) {
* Used by `_.defaultsDeep` to customize its `_.merge` use.
*
* @private
- * @param {*} objectValue The destination object property value.
- * @param {*} sourceValue The source object property value.
- * @returns {*} Returns the value to assign to the destination object.
+ * @param {*} objValue The destination value.
+ * @param {*} srcValue The source value.
+ * @param {string} key The key of the property to merge.
+ * @param {Object} object The parent object of `objValue`.
+ * @param {Object} source The parent object of `srcValue`.
+ * @param {Object} [stack] Tracks traversed source values and their merged counterparts.
+ * @returns {*} Returns the value to assign.
*/
- function mergeDefaults(objectValue, sourceValue) {
- return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
- }
-
- /**
- * A specialized version of `_.pick` which picks `object` properties specified
- * by `props`.
- *
- * @private
- * @param {Object} object The source object.
- * @param {string[]} props The property names to pick.
- * @returns {Object} Returns the new object.
- */
- function pickByArray(object, props) {
- object = toObject(object);
-
- var index = -1,
- length = props.length,
- result = {};
-
- while (++index < length) {
- var key = props[index];
- if (key in object) {
- result[key] = object[key];
- }
+ function mergeDefaults(objValue, srcValue, key, object, source, stack) {
+ if (isObject(objValue) && isObject(srcValue)) {
+ stack.set(srcValue, objValue);
+ baseMerge(objValue, srcValue, undefined, mergeDefaults, stack);
}
- return result;
+ return objValue;
}
/**
- * A specialized version of `_.pick` which picks `object` properties `predicate`
- * returns truthy for.
+ * Gets the parent value at `path` of `object`.
*
* @private
- * @param {Object} object The source object.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {Object} Returns the new object.
+ * @param {Object} object The object to query.
+ * @param {Array} path The path to get the parent value of.
+ * @returns {*} Returns the parent value.
*/
- function pickByCallback(object, predicate) {
- var result = {};
- baseForIn(object, function(value, key, object) {
- if (predicate(value, key, object)) {
- result[key] = value;
- }
- });
- return result;
+ function parent(object, path) {
+ return path.length == 1 ? object : get(object, baseSlice(path, 0, -1));
}
/**
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
- oldArray = arrayCopy(array);
+ oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
}());
/**
- * A fallback implementation of `Object.keys` which creates an array of the
- * own enumerable property names of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- */
- function shimKeys(object) {
- var props = keysIn(object),
- propsLength = props.length,
- length = propsLength && object.length;
-
- var allowIndexes = !!length && isLength(length) &&
- (isArray(object) || isArguments(object));
-
- var index = -1,
- result = [];
-
- while (++index < propsLength) {
- var key = props[index];
- if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
- result.push(key);
- }
- }
- return result;
- }
-
- /**
- * Converts `value` to an array-like object if it's not one.
+ * Converts `string` to a property path array.
*
* @private
- * @param {*} value The value to process.
- * @returns {Array|Object} Returns the array-like object.
- */
- function toIterable(value) {
- if (value == null) {
- return [];
- }
- if (!isArrayLike(value)) {
- return values(value);
- }
- return isObject(value) ? value : Object(value);
- }
-
- /**
- * Converts `value` to an object if it's not one.
- *
- * @private
- * @param {*} value The value to process.
- * @returns {Object} Returns the object.
- */
- function toObject(value) {
- return isObject(value) ? value : Object(value);
- }
-
- /**
- * Converts `value` to property path array if it's not one.
- *
- * @private
- * @param {*} value The value to process.
+ * @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
- function toPath(value) {
- if (isArray(value)) {
- return value;
- }
+ function stringToPath(string) {
var result = [];
- baseToString(value).replace(rePropName, function(match, number, quote, string) {
+ toString(string).replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
- return wrapper instanceof LazyWrapper
- ? wrapper.clone()
- : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
+ if (wrapper instanceof LazyWrapper) {
+ return wrapper.clone();
+ }
+ var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
+ result.__actions__ = copyArray(wrapper.__actions__);
+ result.__index__ = wrapper.__index__;
+ result.__values__ = wrapper.__values__;
+ return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements split into groups the length of `size`.
- * If `collection` can't be split evenly, the final chunk will be the remaining
+ * If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to process.
- * @param {number} [size=1] The length of each chunk.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param {number} [size=0] The length of each chunk.
* @returns {Array} Returns the new array containing chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
- function chunk(array, size, guard) {
- if (guard ? isIterateeCall(array, size, guard) : size == null) {
- size = 1;
- } else {
- size = nativeMax(nativeFloor(size) || 1, 1);
+ function chunk(array, size) {
+ size = nativeMax(toInteger(size), 0);
+
+ var length = array ? array.length : 0;
+ if (!length || size < 1) {
+ return [];
}
var index = 0,
- length = array ? array.length : 0,
resIndex = -1,
result = Array(nativeCeil(length / size));
}
/**
+ * Creates a new array concatenating `array` with any additional arrays
+ * and/or values.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to concatenate.
+ * @param {...*} [values] The values to concatenate.
+ * @returns {Array} Returns the new concatenated array.
+ * @example
+ *
+ * var array = [1];
+ * var other = _.concat(array, 2, [3], [[4]]);
+ *
+ * console.log(other);
+ * // => [1, 2, 3, [4]]
+ *
+ * console.log(array);
+ * // => [1]
+ */
+ var concat = rest(function(array, values) {
+ if (!isArray(array)) {
+ array = array == null ? [] : [Object(array)];
+ }
+ values = baseFlatten(values, 1);
+ return arrayConcat(array, values);
+ });
+
+ /**
* Creates an array of unique `array` values not included in the other
- * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * given arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to inspect.
- * @param {...Array} [values] The arrays of values to exclude.
+ * @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @example
*
- * _.difference([1, 2, 3], [4, 2]);
- * // => [1, 3]
+ * _.difference([3, 2, 1], [4, 2]);
+ * // => [3, 1]
+ */
+ var difference = rest(function(array, values) {
+ return isArrayLikeObject(array)
+ ? baseDifference(array, baseFlatten(values, 1, true))
+ : [];
+ });
+
+ /**
+ * This method is like `_.difference` except that it accepts `iteratee` which
+ * is invoked for each element of `array` and `values` to generate the criterion
+ * by which uniqueness is computed. The iteratee is invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {...Array} [values] The values to exclude.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {Array} Returns the new array of filtered values.
+ * @example
+ *
+ * _.differenceBy([3.1, 2.2, 1.3], [4.4, 2.5], Math.floor);
+ * // => [3.1, 1.3]
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
+ * // => [{ 'x': 2 }]
*/
- var difference = restParam(function(array, values) {
- return (isObjectLike(array) && isArrayLike(array))
- ? baseDifference(array, baseFlatten(values, false, true))
+ var differenceBy = rest(function(array, values) {
+ var iteratee = last(values);
+ if (isArrayLikeObject(iteratee)) {
+ iteratee = undefined;
+ }
+ return isArrayLikeObject(array)
+ ? baseDifference(array, baseFlatten(values, 1, true), getIteratee(iteratee))
+ : [];
+ });
+
+ /**
+ * This method is like `_.difference` except that it accepts `comparator`
+ * which is invoked to compare elements of `array` to `values`. The comparator
+ * is invoked with two arguments: (arrVal, othVal).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {...Array} [values] The values to exclude.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of filtered values.
+ * @example
+ *
+ * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
+ *
+ * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
+ * // => [{ 'x': 2, 'y': 1 }]
+ */
+ var differenceWith = rest(function(array, values) {
+ var comparator = last(values);
+ if (isArrayLikeObject(comparator)) {
+ comparator = undefined;
+ }
+ return isArrayLikeObject(array)
+ ? baseDifference(array, baseFlatten(values, 1, true), undefined, comparator)
: [];
});
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
if (!length) {
return [];
}
- if (guard ? isIterateeCall(array, n, guard) : n == null) {
- n = 1;
- }
- return baseSlice(array, n < 0 ? 0 : n);
+ n = (guard || n === undefined) ? 1 : toInteger(n);
+ return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
if (!length) {
return [];
}
- if (guard ? isIterateeCall(array, n, guard) : n == null) {
- n = 1;
- }
- n = length - (+n || 0);
+ n = (guard || n === undefined) ? 1 : toInteger(n);
+ n = length - n;
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
- * bound to `thisArg` and invoked with three arguments: (value, index, array).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that match the properties of the given
- * object, else `false`.
+ * invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
- * _.dropRightWhile([1, 2, 3], function(n) {
- * return n > 1;
- * });
- * // => [1]
- *
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
- * // using the `_.matches` callback shorthand
- * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
- * // => ['barney', 'fred']
+ * _.dropRightWhile(users, function(o) { return !o.active; });
+ * // => objects for ['barney']
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
+ * // => objects for ['barney', 'fred']
*
- * // using the `_.matchesProperty` callback shorthand
- * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
- * // => ['barney']
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.dropRightWhile(users, ['active', false]);
+ * // => objects for ['barney']
*
- * // using the `_.property` callback shorthand
- * _.pluck(_.dropRightWhile(users, 'active'), 'user');
- * // => ['barney', 'fred', 'pebbles']
+ * // The `_.property` iteratee shorthand.
+ * _.dropRightWhile(users, 'active');
+ * // => objects for ['barney', 'fred', 'pebbles']
*/
- function dropRightWhile(array, predicate, thisArg) {
+ function dropRightWhile(array, predicate) {
return (array && array.length)
- ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
+ ? baseWhile(array, getIteratee(predicate, 3), true, true)
: [];
}
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
- * bound to `thisArg` and invoked with three arguments: (value, index, array).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
- * _.dropWhile([1, 2, 3], function(n) {
- * return n < 3;
- * });
- * // => [3]
- *
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
- * // using the `_.matches` callback shorthand
- * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
- * // => ['fred', 'pebbles']
+ * _.dropWhile(users, function(o) { return !o.active; });
+ * // => objects for ['pebbles']
*
- * // using the `_.matchesProperty` callback shorthand
- * _.pluck(_.dropWhile(users, 'active', false), 'user');
- * // => ['pebbles']
+ * // The `_.matches` iteratee shorthand.
+ * _.dropWhile(users, { 'user': 'barney', 'active': false });
+ * // => objects for ['fred', 'pebbles']
*
- * // using the `_.property` callback shorthand
- * _.pluck(_.dropWhile(users, 'active'), 'user');
- * // => ['barney', 'fred', 'pebbles']
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.dropWhile(users, ['active', false]);
+ * // => objects for ['pebbles']
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.dropWhile(users, 'active');
+ * // => objects for ['barney', 'fred', 'pebbles']
*/
- function dropWhile(array, predicate, thisArg) {
+ function dropWhile(array, predicate) {
return (array && array.length)
- ? baseWhile(array, getCallback(predicate, thisArg, 3), true)
+ ? baseWhile(array, getIteratee(predicate, 3), true)
: [];
}
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
- * _.fill([4, 6, 8], '*', 1, 2);
- * // => [4, '*', 8]
+ * _.fill([4, 6, 8, 10], '*', 1, 3);
+ * // => [4, '*', '*', 10]
*/
function fill(array, value, start, end) {
var length = array ? array.length : 0;
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
- *
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* { 'user': 'pebbles', 'active': true }
* ];
*
- * _.findIndex(users, function(chr) {
- * return chr.user == 'barney';
- * });
+ * _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
- * // using the `_.matches` callback shorthand
+ * // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
- * // using the `_.matchesProperty` callback shorthand
- * _.findIndex(users, 'active', false);
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.findIndex(users, ['active', false]);
* // => 0
*
- * // using the `_.property` callback shorthand
+ * // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
- var findIndex = createFindIndex();
+ function findIndex(array, predicate) {
+ return (array && array.length)
+ ? baseFindIndex(array, getIteratee(predicate, 3))
+ : -1;
+ }
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
- *
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* { 'user': 'pebbles', 'active': false }
* ];
*
- * _.findLastIndex(users, function(chr) {
- * return chr.user == 'pebbles';
- * });
+ * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
- * // using the `_.matches` callback shorthand
+ * // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
- * // using the `_.matchesProperty` callback shorthand
- * _.findLastIndex(users, 'active', false);
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.findLastIndex(users, ['active', false]);
* // => 2
*
- * // using the `_.property` callback shorthand
+ * // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/
- var findLastIndex = createFindIndex(true);
+ function findLastIndex(array, predicate) {
+ return (array && array.length)
+ ? baseFindIndex(array, getIteratee(predicate, 3), true)
+ : -1;
+ }
/**
- * Gets the first element of `array`.
+ * Flattens `array` a single level deep.
*
* @static
* @memberOf _
- * @alias head
* @category Array
- * @param {Array} array The array to query.
- * @returns {*} Returns the first element of `array`.
+ * @param {Array} array The array to flatten.
+ * @returns {Array} Returns the new flattened array.
* @example
*
- * _.first([1, 2, 3]);
- * // => 1
+ * _.flatten([1, [2, [3, [4]], 5]]);
+ * // => [1, 2, [3, [4]], 5]
+ */
+ function flatten(array) {
+ var length = array ? array.length : 0;
+ return length ? baseFlatten(array, 1) : [];
+ }
+
+ /**
+ * Recursively flattens `array`.
*
- * _.first([]);
- * // => undefined
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to flatten.
+ * @returns {Array} Returns the new flattened array.
+ * @example
+ *
+ * _.flattenDeep([1, [2, [3, [4]], 5]]);
+ * // => [1, 2, 3, 4, 5]
*/
- function first(array) {
- return array ? array[0] : undefined;
+ function flattenDeep(array) {
+ var length = array ? array.length : 0;
+ return length ? baseFlatten(array, INFINITY) : [];
}
/**
- * Flattens a nested array. If `isDeep` is `true` the array is recursively
- * flattened, otherwise it's only flattened a single level.
+ * Recursively flatten `array` up to `depth` times.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to flatten.
- * @param {boolean} [isDeep] Specify a deep flatten.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
- * _.flatten([1, [2, 3, [4]]]);
- * // => [1, 2, 3, [4]]
+ * var array = [1, [2, [3, [4]], 5]];
*
- * // using `isDeep`
- * _.flatten([1, [2, 3, [4]]], true);
- * // => [1, 2, 3, 4]
+ * _.flattenDepth(array, 1);
+ * // => [1, 2, [3, [4]], 5]
+ *
+ * _.flattenDepth(array, 2);
+ * // => [1, 2, 3, [4], 5]
*/
- function flatten(array, isDeep, guard) {
+ function flattenDepth(array, depth) {
var length = array ? array.length : 0;
- if (guard && isIterateeCall(array, isDeep, guard)) {
- isDeep = false;
+ if (!length) {
+ return [];
}
- return length ? baseFlatten(array, isDeep) : [];
+ depth = depth === undefined ? 1 : toInteger(depth);
+ return baseFlatten(array, depth);
}
/**
- * Recursively flattens a nested array.
+ * The inverse of `_.toPairs`; this method returns an object composed
+ * from key-value `pairs`.
*
* @static
* @memberOf _
* @category Array
- * @param {Array} array The array to recursively flatten.
- * @returns {Array} Returns the new flattened array.
+ * @param {Array} pairs The key-value pairs.
+ * @returns {Object} Returns the new object.
* @example
*
- * _.flattenDeep([1, [2, 3, [4]]]);
- * // => [1, 2, 3, 4]
+ * _.fromPairs([['fred', 30], ['barney', 40]]);
+ * // => { 'fred': 30, 'barney': 40 }
*/
- function flattenDeep(array) {
- var length = array ? array.length : 0;
- return length ? baseFlatten(array, true) : [];
+ function fromPairs(pairs) {
+ var index = -1,
+ length = pairs ? pairs.length : 0,
+ result = {};
+
+ while (++index < length) {
+ var pair = pairs[index];
+ result[pair[0]] = pair[1];
+ }
+ return result;
+ }
+
+ /**
+ * Gets the first element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @alias first
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {*} Returns the first element of `array`.
+ * @example
+ *
+ * _.head([1, 2, 3]);
+ * // => 1
+ *
+ * _.head([]);
+ * // => undefined
+ */
+ function head(array) {
+ return array ? array[0] : undefined;
}
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the offset
- * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
- * performs a faster binary search.
+ * from the end of `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {*} value The value to search for.
- * @param {boolean|number} [fromIndex=0] The index to search from or `true`
- * to perform a binary search on a sorted array.
+ * @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
- * // using `fromIndex`
+ * // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
- *
- * // performing a binary search
- * _.indexOf([1, 1, 2, 2], 2, true);
- * // => 2
*/
function indexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
- if (typeof fromIndex == 'number') {
- fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
- } else if (fromIndex) {
- var index = binaryIndex(array, value);
- if (index < length &&
- (value === value ? (value === array[index]) : (array[index] !== array[index]))) {
- return index;
- }
- return -1;
+ fromIndex = toInteger(fromIndex);
+ if (fromIndex < 0) {
+ fromIndex = nativeMax(length + fromIndex, 0);
}
- return baseIndexOf(array, value, fromIndex || 0);
+ return baseIndexOf(array, value, fromIndex);
}
/**
}
/**
- * Creates an array of unique values that are included in all of the provided
- * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * Creates an array of unique values that are included in all given arrays
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of shared values.
* @example
- * _.intersection([1, 2], [4, 2], [2, 1]);
+ *
+ * _.intersection([2, 1], [4, 2], [1, 2]);
* // => [2]
*/
- var intersection = restParam(function(arrays) {
- var othLength = arrays.length,
- othIndex = othLength,
- caches = Array(length),
- indexOf = getIndexOf(),
- isCommon = indexOf === baseIndexOf,
- result = [];
+ var intersection = rest(function(arrays) {
+ var mapped = arrayMap(arrays, baseCastArrayLikeObject);
+ return (mapped.length && mapped[0] === arrays[0])
+ ? baseIntersection(mapped)
+ : [];
+ });
- while (othIndex--) {
- var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
- caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
+ /**
+ * This method is like `_.intersection` except that it accepts `iteratee`
+ * which is invoked for each element of each `arrays` to generate the criterion
+ * by which uniqueness is computed. The iteratee is invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {Array} Returns the new array of shared values.
+ * @example
+ *
+ * _.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
+ * // => [2.1]
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
+ * // => [{ 'x': 1 }]
+ */
+ var intersectionBy = rest(function(arrays) {
+ var iteratee = last(arrays),
+ mapped = arrayMap(arrays, baseCastArrayLikeObject);
+
+ if (iteratee === last(mapped)) {
+ iteratee = undefined;
+ } else {
+ mapped.pop();
}
- var array = arrays[0],
- index = -1,
- length = array ? array.length : 0,
- seen = caches[0];
+ return (mapped.length && mapped[0] === arrays[0])
+ ? baseIntersection(mapped, getIteratee(iteratee))
+ : [];
+ });
- outer:
- while (++index < length) {
- value = array[index];
- if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
- var othIndex = othLength;
- while (--othIndex) {
- var cache = caches[othIndex];
- if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
- continue outer;
- }
- }
- if (seen) {
- seen.push(value);
- }
- result.push(value);
- }
+ /**
+ * This method is like `_.intersection` except that it accepts `comparator`
+ * which is invoked to compare elements of `arrays`. The comparator is invoked
+ * with two arguments: (arrVal, othVal).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of shared values.
+ * @example
+ *
+ * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
+ * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
+ *
+ * _.intersectionWith(objects, others, _.isEqual);
+ * // => [{ 'x': 1, 'y': 2 }]
+ */
+ var intersectionWith = rest(function(arrays) {
+ var comparator = last(arrays),
+ mapped = arrayMap(arrays, baseCastArrayLikeObject);
+
+ if (comparator === last(mapped)) {
+ comparator = undefined;
+ } else {
+ mapped.pop();
}
- return result;
+ return (mapped.length && mapped[0] === arrays[0])
+ ? baseIntersection(mapped, undefined, comparator)
+ : [];
});
/**
+ * Converts all elements in `array` into a string separated by `separator`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to convert.
+ * @param {string} [separator=','] The element separator.
+ * @returns {string} Returns the joined string.
+ * @example
+ *
+ * _.join(['a', 'b', 'c'], '~');
+ * // => 'a~b~c'
+ */
+ function join(array, separator) {
+ return array ? nativeJoin.call(array, separator) : '';
+ }
+
+ /**
* Gets the last element of `array`.
*
* @static
* @category Array
* @param {Array} array The array to search.
* @param {*} value The value to search for.
- * @param {boolean|number} [fromIndex=array.length-1] The index to search from
- * or `true` to perform a binary search on a sorted array.
+ * @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
- * // using `fromIndex`
+ * // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
- *
- * // performing a binary search
- * _.lastIndexOf([1, 1, 2, 2], 2, true);
- * // => 3
*/
function lastIndexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
return -1;
}
var index = length;
- if (typeof fromIndex == 'number') {
- index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
- } else if (fromIndex) {
- index = binaryIndex(array, value, true) - 1;
- var other = array[index];
- if (value === value ? (value === other) : (other !== other)) {
- return index;
- }
- return -1;
+ if (fromIndex !== undefined) {
+ index = toInteger(fromIndex);
+ index = (index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1)) + 1;
}
if (value !== value) {
return indexOfNaN(array, index, true);
}
/**
- * Removes all provided values from `array` using
+ * Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
- * **Note:** Unlike `_.without`, this method mutates `array`.
+ * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
+ * to remove elements from an array by predicate.
*
* @static
* @memberOf _
* console.log(array);
* // => [1, 1]
*/
- function pull() {
- var args = arguments,
- array = args[0];
-
- if (!(array && array.length)) {
- return array;
- }
- var index = 0,
- indexOf = getIndexOf(),
- length = args.length;
+ var pull = rest(pullAll);
- while (++index < length) {
- var fromIndex = 0,
- value = args[index];
+ /**
+ * This method is like `_.pull` except that it accepts an array of values to remove.
+ *
+ * **Note:** Unlike `_.difference`, this method mutates `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to remove.
+ * @returns {Array} Returns `array`.
+ * @example
+ *
+ * var array = [1, 2, 3, 1, 2, 3];
+ *
+ * _.pullAll(array, [2, 3]);
+ * console.log(array);
+ * // => [1, 1]
+ */
+ function pullAll(array, values) {
+ return (array && array.length && values && values.length)
+ ? basePullAll(array, values)
+ : array;
+ }
- while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
- splice.call(array, fromIndex, 1);
- }
- }
- return array;
+ /**
+ * This method is like `_.pullAll` except that it accepts `iteratee` which is
+ * invoked for each element of `array` and `values` to generate the criterion
+ * by which uniqueness is computed. The iteratee is invoked with one argument: (value).
+ *
+ * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to remove.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {Array} Returns `array`.
+ * @example
+ *
+ * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
+ *
+ * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
+ * console.log(array);
+ * // => [{ 'x': 2 }]
+ */
+ function pullAllBy(array, values, iteratee) {
+ return (array && array.length && values && values.length)
+ ? basePullAllBy(array, values, getIteratee(iteratee))
+ : array;
}
/**
- * Removes elements from `array` corresponding to the given indexes and returns
- * an array of the removed elements. Indexes may be specified as an array of
- * indexes or as individual arguments.
+ * Removes elements from `array` corresponding to `indexes` and returns an
+ * array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove,
- * specified as individual indexes or arrays of indexes.
+ * specified individually or in arrays.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* console.log(evens);
* // => [10, 20]
*/
- var pullAt = restParam(function(array, indexes) {
- indexes = baseFlatten(indexes);
+ var pullAt = rest(function(array, indexes) {
+ indexes = arrayMap(baseFlatten(indexes, 1), String);
var result = baseAt(array, indexes);
- basePullAt(array, indexes.sort(baseCompareAscending));
+ basePullAt(array, indexes.sort(compareAscending));
return result;
});
/**
* Removes all elements from `array` that `predicate` returns truthy for
- * and returns an array of the removed elements. The predicate is bound to
- * `thisArg` and invoked with three arguments: (value, index, array).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
+ * and returns an array of the removed elements. The predicate is invoked
+ * with three arguments: (value, index, array).
*
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
- *
- * **Note:** Unlike `_.filter`, this method mutates `array`.
+ * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
+ * to pull elements from an array by value.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* console.log(evens);
* // => [2, 4]
*/
- function remove(array, predicate, thisArg) {
+ function remove(array, predicate) {
var result = [];
if (!(array && array.length)) {
return result;
indexes = [],
length = array.length;
- predicate = getCallback(predicate, thisArg, 3);
+ predicate = getIteratee(predicate, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
}
/**
- * Gets all but the first element of `array`.
+ * Reverses `array` so that the first element becomes the last, the second
+ * element becomes the second to last, and so on.
+ *
+ * **Note:** This method mutates `array` and is based on
+ * [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
- * @alias tail
* @category Array
- * @param {Array} array The array to query.
- * @returns {Array} Returns the slice of `array`.
+ * @returns {Array} Returns `array`.
* @example
*
- * _.rest([1, 2, 3]);
- * // => [2, 3]
+ * var array = [1, 2, 3];
+ *
+ * _.reverse(array);
+ * // => [3, 2, 1]
+ *
+ * console.log(array);
+ * // => [3, 2, 1]
*/
- function rest(array) {
- return drop(array, 1);
+ function reverse(array) {
+ return array ? nativeReverse.call(array) : array;
}
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
- * **Note:** This method is used instead of `Array#slice` to support node
- * lists in IE < 9 and to ensure dense arrays are returned.
+ * **Note:** This method is used instead of [`Array#slice`](https://mdn.io/Array/slice)
+ * to ensure dense arrays are returned.
*
* @static
* @memberOf _
start = 0;
end = length;
}
+ else {
+ start = start == null ? 0 : toInteger(start);
+ end = end === undefined ? length : toInteger(end);
+ }
return baseSlice(array, start, end);
}
/**
* Uses a binary search to determine the lowest index at which `value` should
- * be inserted into `array` in order to maintain its sort order. If an iteratee
- * function is provided it's invoked for `value` and each element of `array`
- * to compute their sort ranking. The iteratee is bound to `thisArg` and
- * invoked with one argument; (value).
- *
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * be inserted into `array` in order to maintain its sort order.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
- * @returns {number} Returns the index at which `value` should be inserted
- * into `array`.
+ * @returns {number} Returns the index at which `value` should be inserted into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*
- * _.sortedIndex([4, 4, 5, 5], 5);
- * // => 2
+ * _.sortedIndex([4, 5], 4);
+ * // => 0
+ */
+ function sortedIndex(array, value) {
+ return baseSortedIndex(array, value);
+ }
+
+ /**
+ * This method is like `_.sortedIndex` except that it accepts `iteratee`
+ * which is invoked for `value` and each element of `array` to compute their
+ * sort ranking. The iteratee is invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {number} Returns the index at which `value` should be inserted into `array`.
+ * @example
*
- * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
+ * var dict = { 'thirty': 30, 'forty': 40, 'fifty': 50 };
*
- * // using an iteratee function
- * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
- * return this.data[word];
- * }, dict);
+ * _.sortedIndexBy(['thirty', 'fifty'], 'forty', _.propertyOf(dict));
* // => 1
*
- * // using the `_.property` callback shorthand
- * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
- * // => 1
+ * // The `_.property` iteratee shorthand.
+ * _.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
+ * // => 0
+ */
+ function sortedIndexBy(array, value, iteratee) {
+ return baseSortedIndexBy(array, value, getIteratee(iteratee));
+ }
+
+ /**
+ * This method is like `_.indexOf` except that it performs a binary
+ * search on a sorted `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to search.
+ * @param {*} value The value to search for.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ * @example
+ *
+ * _.sortedIndexOf([1, 1, 2, 2], 2);
+ * // => 2
*/
- var sortedIndex = createSortedIndex();
+ function sortedIndexOf(array, value) {
+ var length = array ? array.length : 0;
+ if (length) {
+ var index = baseSortedIndex(array, value);
+ if (index < length && eq(array[index], value)) {
+ return index;
+ }
+ }
+ return -1;
+ }
/**
* This method is like `_.sortedIndex` except that it returns the highest
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
- * @returns {number} Returns the index at which `value` should be inserted
- * into `array`.
+ * @returns {number} Returns the index at which `value` should be inserted into `array`.
* @example
*
- * _.sortedLastIndex([4, 4, 5, 5], 5);
- * // => 4
+ * _.sortedLastIndex([4, 5], 4);
+ * // => 1
+ */
+ function sortedLastIndex(array, value) {
+ return baseSortedIndex(array, value, true);
+ }
+
+ /**
+ * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
+ * which is invoked for `value` and each element of `array` to compute their
+ * sort ranking. The iteratee is invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {number} Returns the index at which `value` should be inserted into `array`.
+ * @example
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
+ * // => 1
+ */
+ function sortedLastIndexBy(array, value, iteratee) {
+ return baseSortedIndexBy(array, value, getIteratee(iteratee), true);
+ }
+
+ /**
+ * This method is like `_.lastIndexOf` except that it performs a binary
+ * search on a sorted `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to search.
+ * @param {*} value The value to search for.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ * @example
+ *
+ * _.sortedLastIndexOf([1, 1, 2, 2], 2);
+ * // => 3
+ */
+ function sortedLastIndexOf(array, value) {
+ var length = array ? array.length : 0;
+ if (length) {
+ var index = baseSortedIndex(array, value, true) - 1;
+ if (eq(array[index], value)) {
+ return index;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * This method is like `_.uniq` except that it's designed and optimized
+ * for sorted arrays.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @returns {Array} Returns the new duplicate free array.
+ * @example
+ *
+ * _.sortedUniq([1, 1, 2]);
+ * // => [1, 2]
+ */
+ function sortedUniq(array) {
+ return (array && array.length)
+ ? baseSortedUniq(array)
+ : [];
+ }
+
+ /**
+ * This method is like `_.uniqBy` except that it's designed and optimized
+ * for sorted arrays.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @returns {Array} Returns the new duplicate free array.
+ * @example
+ *
+ * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
+ * // => [1.1, 2.3]
*/
- var sortedLastIndex = createSortedIndex(true);
+ function sortedUniqBy(array, iteratee) {
+ return (array && array.length)
+ ? baseSortedUniqBy(array, getIteratee(iteratee))
+ : [];
+ }
+
+ /**
+ * Gets all but the first element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.tail([1, 2, 3]);
+ * // => [2, 3]
+ */
+ function tail(array) {
+ return drop(array, 1);
+ }
/**
* Creates a slice of `array` with `n` elements taken from the beginning.
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* // => []
*/
function take(array, n, guard) {
- var length = array ? array.length : 0;
- if (!length) {
+ if (!(array && array.length)) {
return [];
}
- if (guard ? isIterateeCall(array, n, guard) : n == null) {
- n = 1;
- }
+ n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, 0, n < 0 ? 0 : n);
}
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
if (!length) {
return [];
}
- if (guard ? isIterateeCall(array, n, guard) : n == null) {
- n = 1;
- }
- n = length - (+n || 0);
- return baseSlice(array, n < 0 ? 0 : n);
+ n = (guard || n === undefined) ? 1 : toInteger(n);
+ n = length - n;
+ return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with elements taken from the end. Elements are
- * taken until `predicate` returns falsey. The predicate is bound to `thisArg`
- * and invoked with three arguments: (value, index, array).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * taken until `predicate` returns falsey. The predicate is invoked with three
+ * arguments: (value, index, array).
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
- * _.takeRightWhile([1, 2, 3], function(n) {
- * return n > 1;
- * });
- * // => [2, 3]
- *
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
- * // using the `_.matches` callback shorthand
- * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
- * // => ['pebbles']
+ * _.takeRightWhile(users, function(o) { return !o.active; });
+ * // => objects for ['fred', 'pebbles']
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
+ * // => objects for ['pebbles']
*
- * // using the `_.matchesProperty` callback shorthand
- * _.pluck(_.takeRightWhile(users, 'active', false), 'user');
- * // => ['fred', 'pebbles']
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.takeRightWhile(users, ['active', false]);
+ * // => objects for ['fred', 'pebbles']
*
- * // using the `_.property` callback shorthand
- * _.pluck(_.takeRightWhile(users, 'active'), 'user');
+ * // The `_.property` iteratee shorthand.
+ * _.takeRightWhile(users, 'active');
* // => []
*/
- function takeRightWhile(array, predicate, thisArg) {
+ function takeRightWhile(array, predicate) {
return (array && array.length)
- ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
+ ? baseWhile(array, getIteratee(predicate, 3), false, true)
: [];
}
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
- * are taken until `predicate` returns falsey. The predicate is bound to
- * `thisArg` and invoked with three arguments: (value, index, array).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * are taken until `predicate` returns falsey. The predicate is invoked with
+ * three arguments: (value, index, array).
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
- * _.takeWhile([1, 2, 3], function(n) {
- * return n < 3;
- * });
- * // => [1, 2]
- *
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false},
* { 'user': 'pebbles', 'active': true }
* ];
*
- * // using the `_.matches` callback shorthand
- * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
- * // => ['barney']
+ * _.takeWhile(users, function(o) { return !o.active; });
+ * // => objects for ['barney', 'fred']
*
- * // using the `_.matchesProperty` callback shorthand
- * _.pluck(_.takeWhile(users, 'active', false), 'user');
- * // => ['barney', 'fred']
+ * // The `_.matches` iteratee shorthand.
+ * _.takeWhile(users, { 'user': 'barney', 'active': false });
+ * // => objects for ['barney']
*
- * // using the `_.property` callback shorthand
- * _.pluck(_.takeWhile(users, 'active'), 'user');
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.takeWhile(users, ['active', false]);
+ * // => objects for ['barney', 'fred']
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.takeWhile(users, 'active');
* // => []
*/
- function takeWhile(array, predicate, thisArg) {
+ function takeWhile(array, predicate) {
return (array && array.length)
- ? baseWhile(array, getCallback(predicate, thisArg, 3))
+ ? baseWhile(array, getIteratee(predicate, 3))
: [];
}
/**
- * Creates an array of unique values, in order, from all of the provided arrays
- * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * Creates an array of unique values, in order, from all given arrays using
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @returns {Array} Returns the new array of combined values.
* @example
*
- * _.union([1, 2], [4, 2], [2, 1]);
- * // => [1, 2, 4]
+ * _.union([2, 1], [4, 2], [1, 2]);
+ * // => [2, 1, 4]
*/
- var union = restParam(function(arrays) {
- return baseUniq(baseFlatten(arrays, false, true));
+ var union = rest(function(arrays) {
+ return baseUniq(baseFlatten(arrays, 1, true));
});
/**
- * Creates a duplicate-free version of an array, using
- * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
- * for equality comparisons, in which only the first occurence of each element
- * is kept. Providing `true` for `isSorted` performs a faster search algorithm
- * for sorted arrays. If an iteratee function is provided it's invoked for
- * each element in the array to generate the criterion by which uniqueness
- * is computed. The `iteratee` is bound to `thisArg` and invoked with three
- * arguments: (value, index, array).
+ * This method is like `_.union` except that it accepts `iteratee` which is
+ * invoked for each element of each `arrays` to generate the criterion by which
+ * uniqueness is computed. The iteratee is invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {Array} Returns the new array of combined values.
+ * @example
*
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
+ * _.unionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
+ * // => [2.1, 1.2, 4.3]
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
+ * // => [{ 'x': 1 }, { 'x': 2 }]
+ */
+ var unionBy = rest(function(arrays) {
+ var iteratee = last(arrays);
+ if (isArrayLikeObject(iteratee)) {
+ iteratee = undefined;
+ }
+ return baseUniq(baseFlatten(arrays, 1, true), getIteratee(iteratee));
+ });
+
+ /**
+ * This method is like `_.union` except that it accepts `comparator` which
+ * is invoked to compare elements of `arrays`. The comparator is invoked
+ * with two arguments: (arrVal, othVal).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of combined values.
+ * @example
*
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
+ * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
+ * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * _.unionWith(objects, others, _.isEqual);
+ * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
+ */
+ var unionWith = rest(function(arrays) {
+ var comparator = last(arrays);
+ if (isArrayLikeObject(comparator)) {
+ comparator = undefined;
+ }
+ return baseUniq(baseFlatten(arrays, 1, true), undefined, comparator);
+ });
+
+ /**
+ * Creates a duplicate-free version of an array, using
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons, in which only the first occurrence of each element
+ * is kept.
*
* @static
* @memberOf _
- * @alias unique
* @category Array
* @param {Array} array The array to inspect.
- * @param {boolean} [isSorted] Specify the array is sorted.
- * @param {Function|Object|string} [iteratee] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
- * @returns {Array} Returns the new duplicate-value-free array.
+ * @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
+ */
+ function uniq(array) {
+ return (array && array.length)
+ ? baseUniq(array)
+ : [];
+ }
+
+ /**
+ * This method is like `_.uniq` except that it accepts `iteratee` which is
+ * invoked for each element in `array` to generate the criterion by which
+ * uniqueness is computed. The iteratee is invoked with one argument: (value).
*
- * // using `isSorted`
- * _.uniq([1, 1, 2], true);
- * // => [1, 2]
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {Array} Returns the new duplicate free array.
+ * @example
*
- * // using an iteratee function
- * _.uniq([1, 2.5, 1.5, 2], function(n) {
- * return this.floor(n);
- * }, Math);
- * // => [1, 2.5]
+ * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
+ * // => [2.1, 1.2]
*
- * // using the `_.property` callback shorthand
- * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
+ * // The `_.property` iteratee shorthand.
+ * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
- function uniq(array, isSorted, iteratee, thisArg) {
- var length = array ? array.length : 0;
- if (!length) {
- return [];
- }
- if (isSorted != null && typeof isSorted != 'boolean') {
- thisArg = iteratee;
- iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
- isSorted = false;
- }
- var callback = getCallback();
- if (!(iteratee == null && callback === baseCallback)) {
- iteratee = callback(iteratee, thisArg, 3);
- }
- return (isSorted && getIndexOf() === baseIndexOf)
- ? sortedUniq(array, iteratee)
- : baseUniq(array, iteratee);
+ function uniqBy(array, iteratee) {
+ return (array && array.length)
+ ? baseUniq(array, getIteratee(iteratee))
+ : [];
+ }
+
+ /**
+ * This method is like `_.uniq` except that it accepts `comparator` which
+ * is invoked to compare elements of `array`. The comparator is invoked with
+ * two arguments: (arrVal, othVal).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new duplicate free array.
+ * @example
+ *
+ * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
+ *
+ * _.uniqWith(objects, _.isEqual);
+ * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
+ */
+ function uniqWith(array, comparator) {
+ return (array && array.length)
+ ? baseUniq(array, undefined, comparator)
+ : [];
}
/**
if (!(array && array.length)) {
return [];
}
- var index = -1,
- length = 0;
-
+ var length = 0;
array = arrayFilter(array, function(group) {
- if (isArrayLike(group)) {
+ if (isArrayLikeObject(group)) {
length = nativeMax(group.length, length);
return true;
}
});
- var result = Array(length);
- while (++index < length) {
- result[index] = arrayMap(array, baseProperty(index));
- }
- return result;
+ return baseTimes(length, function(index) {
+ return arrayMap(array, baseProperty(index));
+ });
}
/**
- * This method is like `_.unzip` except that it accepts an iteratee to specify
- * how regrouped values should be combined. The `iteratee` is bound to `thisArg`
- * and invoked with four arguments: (accumulator, value, index, group).
+ * This method is like `_.unzip` except that it accepts `iteratee` to specify
+ * how regrouped values should be combined. The iteratee is invoked with the
+ * elements of each group: (...group).
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array of grouped elements to process.
- * @param {Function} [iteratee] The function to combine regrouped values.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Function} [iteratee=_.identity] The function to combine regrouped values.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
*/
- function unzipWith(array, iteratee, thisArg) {
- var length = array ? array.length : 0;
- if (!length) {
+ function unzipWith(array, iteratee) {
+ if (!(array && array.length)) {
return [];
}
var result = unzip(array);
if (iteratee == null) {
return result;
}
- iteratee = bindCallback(iteratee, thisArg, 4);
return arrayMap(result, function(group) {
- return arrayReduce(group, iteratee, undefined, true);
+ return apply(iteratee, undefined, group);
});
}
/**
- * Creates an array excluding all provided values using
+ * Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* _.without([1, 2, 1, 3], 1, 2);
* // => [3]
*/
- var without = restParam(function(array, values) {
- return isArrayLike(array)
+ var without = rest(function(array, values) {
+ return isArrayLikeObject(array)
? baseDifference(array, values)
: [];
});
/**
* Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
- * of the provided arrays.
+ * of the given arrays.
*
* @static
* @memberOf _
* @returns {Array} Returns the new array of values.
* @example
*
- * _.xor([1, 2], [4, 2]);
+ * _.xor([2, 1], [4, 2]);
* // => [1, 4]
*/
- function xor() {
- var index = -1,
- length = arguments.length;
+ var xor = rest(function(arrays) {
+ return baseXor(arrayFilter(arrays, isArrayLikeObject));
+ });
- while (++index < length) {
- var array = arguments[index];
- if (isArrayLike(array)) {
- var result = result
- ? arrayPush(baseDifference(result, array), baseDifference(array, result))
- : array;
- }
+ /**
+ * This method is like `_.xor` except that it accepts `iteratee` which is
+ * invoked for each element of each `arrays` to generate the criterion by which
+ * uniqueness is computed. The iteratee is invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {Array} Returns the new array of values.
+ * @example
+ *
+ * _.xorBy([2.1, 1.2], [4.3, 2.4], Math.floor);
+ * // => [1.2, 4.3]
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
+ * // => [{ 'x': 2 }]
+ */
+ var xorBy = rest(function(arrays) {
+ var iteratee = last(arrays);
+ if (isArrayLikeObject(iteratee)) {
+ iteratee = undefined;
}
- return result ? baseUniq(result) : [];
- }
+ return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee));
+ });
+
+ /**
+ * This method is like `_.xor` except that it accepts `comparator` which is
+ * invoked to compare elements of `arrays`. The comparator is invoked with
+ * two arguments: (arrVal, othVal).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of values.
+ * @example
+ *
+ * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
+ * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
+ *
+ * _.xorWith(objects, others, _.isEqual);
+ * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
+ */
+ var xorWith = rest(function(arrays) {
+ var comparator = last(arrays);
+ if (isArrayLikeObject(comparator)) {
+ comparator = undefined;
+ }
+ return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
+ });
/**
* Creates an array of grouped elements, the first of which contains the first
* _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*/
- var zip = restParam(unzip);
+ var zip = rest(unzip);
/**
- * The inverse of `_.pairs`; this method returns an object composed from arrays
- * of property names and values. Provide either a single two dimensional array,
- * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
- * and one of corresponding values.
+ * This method is like `_.fromPairs` except that it accepts two arrays,
+ * one of property names and one of corresponding values.
*
* @static
* @memberOf _
- * @alias object
* @category Array
- * @param {Array} props The property names.
+ * @param {Array} [props=[]] The property names.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
- * _.zipObject([['fred', 30], ['barney', 40]]);
- * // => { 'fred': 30, 'barney': 40 }
- *
- * _.zipObject(['fred', 'barney'], [30, 40]);
- * // => { 'fred': 30, 'barney': 40 }
+ * _.zipObject(['a', 'b'], [1, 2]);
+ * // => { 'a': 1, 'b': 2 }
*/
function zipObject(props, values) {
- var index = -1,
- length = props ? props.length : 0,
- result = {};
+ return baseZipObject(props || [], values || [], assignValue);
+ }
- if (length && !values && !isArray(props[0])) {
- values = [];
- }
- while (++index < length) {
- var key = props[index];
- if (values) {
- result[key] = values[index];
- } else if (key) {
- result[key[0]] = key[1];
- }
- }
- return result;
+ /**
+ * This method is like `_.zipObject` except that it supports property paths.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} [props=[]] The property names.
+ * @param {Array} [values=[]] The property values.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
+ * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
+ */
+ function zipObjectDeep(props, values) {
+ return baseZipObject(props || [], values || [], baseSet);
}
/**
- * This method is like `_.zip` except that it accepts an iteratee to specify
- * how grouped values should be combined. The `iteratee` is bound to `thisArg`
- * and invoked with four arguments: (accumulator, value, index, group).
+ * This method is like `_.zip` except that it accepts `iteratee` to specify
+ * how grouped values should be combined. The iteratee is invoked with the
+ * elements of each group: (...group).
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to process.
- * @param {Function} [iteratee] The function to combine grouped values.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Function} [iteratee=_.identity] The function to combine grouped values.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
- * _.zipWith([1, 2], [10, 20], [100, 200], _.add);
+ * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
+ * return a + b + c;
+ * });
* // => [111, 222]
*/
- var zipWith = restParam(function(arrays) {
+ var zipWith = rest(function(arrays) {
var length = arrays.length,
- iteratee = length > 2 ? arrays[length - 2] : undefined,
- thisArg = length > 1 ? arrays[length - 1] : undefined;
+ iteratee = length > 1 ? arrays[length - 1] : undefined;
- if (length > 2 && typeof iteratee == 'function') {
- length -= 2;
- } else {
- iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
- thisArg = undefined;
- }
- arrays.length = length;
- return unzipWith(arrays, iteratee, thisArg);
+ iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
+ return unzipWith(arrays, iteratee);
});
/*------------------------------------------------------------------------*/
/**
- * Creates a `lodash` object that wraps `value` with explicit method
- * chaining enabled.
+ * Creates a `lodash` object that wraps `value` with explicit method chaining enabled.
+ * The result of such method chaining must be unwrapped with `_#value`.
*
* @static
* @memberOf _
- * @category Chain
+ * @category Seq
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
* { 'user': 'pebbles', 'age': 1 }
* ];
*
- * var youngest = _.chain(users)
+ * var youngest = _
+ * .chain(users)
* .sortBy('age')
- * .map(function(chr) {
- * return chr.user + ' is ' + chr.age;
+ * .map(function(o) {
+ * return o.user + ' is ' + o.age;
* })
- * .first()
+ * .head()
* .value();
* // => 'pebbles is 1'
*/
}
/**
- * This method invokes `interceptor` and returns `value`. The interceptor is
- * bound to `thisArg` and invoked with one argument; (value). The purpose of
- * this method is to "tap into" a method chain in order to perform operations
- * on intermediate results within the chain.
+ * This method invokes `interceptor` and returns `value`. The interceptor
+ * is invoked with one argument; (value). The purpose of this method is to
+ * "tap into" a method chain in order to modify intermediate results.
*
* @static
* @memberOf _
- * @category Chain
+ * @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
- * @param {*} [thisArg] The `this` binding of `interceptor`.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
+ * // Mutate input array.
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/
- function tap(value, interceptor, thisArg) {
- interceptor.call(thisArg, value);
+ function tap(value, interceptor) {
+ interceptor(value);
return value;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
+ * The purpose of this method is to "pass thru" values replacing intermediate
+ * results in a method chain.
*
* @static
* @memberOf _
- * @category Chain
+ * @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
- * @param {*} [thisArg] The `this` binding of `interceptor`.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* .value();
* // => ['abc']
*/
- function thru(value, interceptor, thisArg) {
- return interceptor.call(thisArg, value);
+ function thru(value, interceptor) {
+ return interceptor(value);
}
/**
+ * This method is the wrapper version of `_.at`.
+ *
+ * @name at
+ * @memberOf _
+ * @category Seq
+ * @param {...(string|string[])} [paths] The property paths of elements to pick,
+ * specified individually or in arrays.
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
+ *
+ * _(object).at(['a[0].b.c', 'a[1]']).value();
+ * // => [3, 4]
+ *
+ * _(['a', 'b', 'c']).at(0, 2).value();
+ * // => ['a', 'c']
+ */
+ var wrapperAt = rest(function(paths) {
+ paths = baseFlatten(paths, 1);
+ var length = paths.length,
+ start = length ? paths[0] : 0,
+ value = this.__wrapped__,
+ interceptor = function(object) { return baseAt(object, paths); };
+
+ if (length > 1 || this.__actions__.length ||
+ !(value instanceof LazyWrapper) || !isIndex(start)) {
+ return this.thru(interceptor);
+ }
+ value = value.slice(start, +start + (length ? 1 : 0));
+ value.__actions__.push({
+ 'func': thru,
+ 'args': [interceptor],
+ 'thisArg': undefined
+ });
+ return new LodashWrapper(value, this.__chain__).thru(function(array) {
+ if (length && !array.length) {
+ array.push(undefined);
+ }
+ return array;
+ });
+ });
+
+ /**
* Enables explicit method chaining on the wrapper object.
*
* @name chain
* @memberOf _
- * @category Chain
+ * @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* { 'user': 'fred', 'age': 40 }
* ];
*
- * // without explicit chaining
- * _(users).first();
+ * // A sequence without explicit chaining.
+ * _(users).head();
* // => { 'user': 'barney', 'age': 36 }
*
- * // with explicit chaining
- * _(users).chain()
- * .first()
+ * // A sequence with explicit chaining.
+ * _(users)
+ * .chain()
+ * .head()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*
* @name commit
* @memberOf _
- * @category Chain
+ * @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
}
/**
- * Creates a new array joining a wrapped array with any additional arrays
- * and/or values.
+ * This method is the wrapper version of `_.flatMap`.
*
- * @name concat
+ * @name flatMap
* @memberOf _
- * @category Chain
- * @param {...*} [values] The values to concatenate.
- * @returns {Array} Returns the new concatenated array.
+ * @category Seq
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
+ * @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
- * var array = [1];
- * var wrapped = _(array).concat(2, [3], [[4]]);
+ * function duplicate(n) {
+ * return [n, n];
+ * }
*
- * console.log(wrapped.value());
- * // => [1, 2, 3, [4]]
+ * _([1, 2]).flatMap(duplicate).value();
+ * // => [1, 1, 2, 2]
+ */
+ function wrapperFlatMap(iteratee) {
+ return this.map(iteratee).flatten();
+ }
+
+ /**
+ * Gets the next value on a wrapped object following the
+ * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
*
- * console.log(array);
- * // => [1]
+ * @name next
+ * @memberOf _
+ * @category Seq
+ * @returns {Object} Returns the next iterator value.
+ * @example
+ *
+ * var wrapped = _([1, 2]);
+ *
+ * wrapped.next();
+ * // => { 'done': false, 'value': 1 }
+ *
+ * wrapped.next();
+ * // => { 'done': false, 'value': 2 }
+ *
+ * wrapped.next();
+ * // => { 'done': true, 'value': undefined }
*/
- var wrapperConcat = restParam(function(values) {
- values = baseFlatten(values);
- return this.thru(function(array) {
- return arrayConcat(isArray(array) ? array : [toObject(array)], values);
- });
- });
+ function wrapperNext() {
+ if (this.__values__ === undefined) {
+ this.__values__ = toArray(this.value());
+ }
+ var done = this.__index__ >= this.__values__.length,
+ value = done ? undefined : this.__values__[this.__index__++];
+
+ return { 'done': done, 'value': value };
+ }
+
+ /**
+ * Enables the wrapper to be iterable.
+ *
+ * @name Symbol.iterator
+ * @memberOf _
+ * @category Seq
+ * @returns {Object} Returns the wrapper object.
+ * @example
+ *
+ * var wrapped = _([1, 2]);
+ *
+ * wrapped[Symbol.iterator]() === wrapped;
+ * // => true
+ *
+ * Array.from(wrapped);
+ * // => [1, 2]
+ */
+ function wrapperToIterator() {
+ return this;
+ }
/**
* Creates a clone of the chained sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
- * @category Chain
+ * @category Seq
+ * @param {*} value The value to plant.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
- * var array = [1, 2];
- * var wrapped = _(array).map(function(value) {
- * return Math.pow(value, 2);
- * });
+ * function square(n) {
+ * return n * n;
+ * }
*
- * var other = [3, 4];
- * var otherWrapped = wrapped.plant(other);
+ * var wrapped = _([1, 2]).map(square);
+ * var other = wrapped.plant([3, 4]);
*
- * otherWrapped.value();
+ * other.value();
* // => [9, 16]
*
* wrapped.value();
while (parent instanceof baseLodash) {
var clone = wrapperClone(parent);
+ clone.__index__ = 0;
+ clone.__values__ = undefined;
if (result) {
previous.__wrapped__ = clone;
} else {
}
/**
- * Reverses the wrapped array so the first element becomes the last, the
- * second element becomes the second to last, and so on.
+ * This method is the wrapper version of `_.reverse`.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
- * @category Chain
- * @returns {Object} Returns the new reversed `lodash` wrapper instance.
+ * @category Seq
+ * @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*/
function wrapperReverse() {
var value = this.__wrapped__;
-
- var interceptor = function(value) {
- return value.reverse();
- };
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
- wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
+ wrapped.__actions__.push({
+ 'func': thru,
+ 'args': [reverse],
+ 'thisArg': undefined
+ });
return new LodashWrapper(wrapped, this.__chain__);
}
- return this.thru(interceptor);
- }
-
- /**
- * Produces the result of coercing the unwrapped value to a string.
- *
- * @name toString
- * @memberOf _
- * @category Chain
- * @returns {string} Returns the coerced string value.
- * @example
- *
- * _([1, 2, 3]).toString();
- * // => '1,2,3'
- */
- function wrapperToString() {
- return (this.value() + '');
+ return this.thru(reverse);
}
/**
*
* @name value
* @memberOf _
- * @alias run, toJSON, valueOf
- * @category Chain
+ * @alias toJSON, valueOf
+ * @category Seq
* @returns {*} Returns the resolved unwrapped value.
* @example
*
/*------------------------------------------------------------------------*/
/**
- * Creates an array of elements corresponding to the given keys, or indexes,
- * of `collection`. Keys may be specified as individual arguments or as arrays
- * of keys.
- *
- * @static
- * @memberOf _
- * @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {...(number|number[]|string|string[])} [props] The property names
- * or indexes of elements to pick, specified individually or in arrays.
- * @returns {Array} Returns the new array of picked elements.
- * @example
- *
- * _.at(['a', 'b', 'c'], [0, 2]);
- * // => ['a', 'c']
- *
- * _.at(['barney', 'fred', 'pebbles'], 0, 2);
- * // => ['barney', 'pebbles']
- */
- var at = restParam(function(collection, props) {
- return baseAt(collection, baseFlatten(props));
- });
-
- /**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is the number of times the key was returned by `iteratee`.
- * The `iteratee` is bound to `thisArg` and invoked with three arguments:
- * (value, index|key, collection).
- *
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
- * _.countBy([4.3, 6.1, 6.4], function(n) {
- * return Math.floor(n);
- * });
- * // => { '4': 1, '6': 2 }
- *
- * _.countBy([4.3, 6.1, 6.4], function(n) {
- * return this.floor(n);
- * }, Math);
+ * _.countBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
- * The predicate is bound to `thisArg` and invoked with three arguments:
- * (value, index|key, collection).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * Iteration is stopped once `predicate` returns falsey. The predicate is
+ * invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
- * @alias all
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
- * @returns {boolean} Returns `true` if all elements pass the predicate check,
- * else `false`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check, else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* { 'user': 'fred', 'active': false }
* ];
*
- * // using the `_.matches` callback shorthand
+ * // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
- * // using the `_.matchesProperty` callback shorthand
- * _.every(users, 'active', false);
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.every(users, ['active', false]);
* // => true
*
- * // using the `_.property` callback shorthand
+ * // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
- function every(collection, predicate, thisArg) {
+ function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
- if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
+ if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
- if (typeof predicate != 'function' || thisArg !== undefined) {
- predicate = getCallback(predicate, thisArg, 3);
- }
- return func(collection, predicate);
+ return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning an array of all elements
- * `predicate` returns truthy for. The predicate is bound to `thisArg` and
- * invoked with three arguments: (value, index|key, collection).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * `predicate` returns truthy for. The predicate is invoked with three arguments:
+ * (value, index|key, collection).
*
* @static
* @memberOf _
- * @alias select
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @example
*
- * _.filter([4, 5, 6], function(n) {
- * return n % 2 == 0;
- * });
- * // => [4, 6]
- *
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
- * // using the `_.matches` callback shorthand
- * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
- * // => ['barney']
+ * _.filter(users, function(o) { return !o.active; });
+ * // => objects for ['fred']
*
- * // using the `_.matchesProperty` callback shorthand
- * _.pluck(_.filter(users, 'active', false), 'user');
- * // => ['fred']
+ * // The `_.matches` iteratee shorthand.
+ * _.filter(users, { 'age': 36, 'active': true });
+ * // => objects for ['barney']
*
- * // using the `_.property` callback shorthand
- * _.pluck(_.filter(users, 'active'), 'user');
- * // => ['barney']
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.filter(users, ['active', false]);
+ * // => objects for ['fred']
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.filter(users, 'active');
+ * // => objects for ['barney']
*/
- function filter(collection, predicate, thisArg) {
+ function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
- predicate = getCallback(predicate, thisArg, 3);
- return func(collection, predicate);
+ return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning the first element
- * `predicate` returns truthy for. The predicate is bound to `thisArg` and
- * invoked with three arguments: (value, index|key, collection).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * `predicate` returns truthy for. The predicate is invoked with three arguments:
+ * (value, index|key, collection).
*
* @static
* @memberOf _
- * @alias detect
* @category Collection
- * @param {Array|Object|string} collection The collection to search.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Array|Object} collection The collection to search.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
- * _.result(_.find(users, function(chr) {
- * return chr.age < 40;
- * }), 'user');
- * // => 'barney'
+ * _.find(users, function(o) { return o.age < 40; });
+ * // => object for 'barney'
*
- * // using the `_.matches` callback shorthand
- * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
- * // => 'pebbles'
+ * // The `_.matches` iteratee shorthand.
+ * _.find(users, { 'age': 1, 'active': true });
+ * // => object for 'pebbles'
*
- * // using the `_.matchesProperty` callback shorthand
- * _.result(_.find(users, 'active', false), 'user');
- * // => 'fred'
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.find(users, ['active', false]);
+ * // => object for 'fred'
*
- * // using the `_.property` callback shorthand
- * _.result(_.find(users, 'active'), 'user');
- * // => 'barney'
+ * // The `_.property` iteratee shorthand.
+ * _.find(users, 'active');
+ * // => object for 'barney'
*/
- var find = createFind(baseEach);
+ function find(collection, predicate) {
+ predicate = getIteratee(predicate, 3);
+ if (isArray(collection)) {
+ var index = baseFindIndex(collection, predicate);
+ return index > -1 ? collection[index] : undefined;
+ }
+ return baseFind(collection, predicate, baseEach);
+ }
/**
* This method is like `_.find` except that it iterates over elements of
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to search.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Array|Object} collection The collection to search.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* });
* // => 3
*/
- var findLast = createFind(baseEachRight, true);
+ function findLast(collection, predicate) {
+ predicate = getIteratee(predicate, 3);
+ if (isArray(collection)) {
+ var index = baseFindIndex(collection, predicate, true);
+ return index > -1 ? collection[index] : undefined;
+ }
+ return baseFind(collection, predicate, baseEachRight);
+ }
/**
- * Performs a deep comparison between each element in `collection` and the
- * source object, returning the first element that has equivalent property
- * values.
- *
- * **Note:** This method supports comparing arrays, booleans, `Date` objects,
- * numbers, `Object` objects, regexes, and strings. Objects are compared by
- * their own, not inherited, enumerable properties. For comparing a single
- * own or inherited property value see `_.matchesProperty`.
+ * Creates an array of flattened values by running each element in `collection`
+ * through `iteratee` and concating its result to the other mapped values.
+ * The iteratee is invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to search.
- * @param {Object} source The object of property values to match.
- * @returns {*} Returns the matched element, else `undefined`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
+ * @returns {Array} Returns the new flattened array.
* @example
*
- * var users = [
- * { 'user': 'barney', 'age': 36, 'active': true },
- * { 'user': 'fred', 'age': 40, 'active': false }
- * ];
- *
- * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
- * // => 'barney'
+ * function duplicate(n) {
+ * return [n, n];
+ * }
*
- * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
- * // => 'fred'
+ * _.flatMap([1, 2], duplicate);
+ * // => [1, 1, 2, 2]
*/
- function findWhere(collection, source) {
- return find(collection, baseMatches(source));
+ function flatMap(collection, iteratee) {
+ return baseFlatten(map(collection, iteratee), 1);
}
/**
* Iterates over elements of `collection` invoking `iteratee` for each element.
- * The `iteratee` is bound to `thisArg` and invoked with three arguments:
- * (value, index|key, collection). Iteratee functions may exit iteration early
- * by explicitly returning `false`.
+ * The iteratee is invoked with three arguments: (value, index|key, collection).
+ * Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length" property
- * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
- * may be used for object iteration.
+ * are iterated like arrays. To avoid this behavior use `_.forIn` or `_.forOwn`
+ * for object iteration.
*
* @static
* @memberOf _
* @alias each
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
- * @returns {Array|Object|string} Returns `collection`.
+ * @returns {Array|Object} Returns `collection`.
* @example
*
- * _([1, 2]).forEach(function(n) {
- * console.log(n);
- * }).value();
- * // => logs each value from left to right and returns the array
+ * _([1, 2]).forEach(function(value) {
+ * console.log(value);
+ * });
+ * // => logs `1` then `2`
*
- * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
- * console.log(n, key);
+ * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
+ * console.log(key);
* });
- * // => logs each value-key pair and returns the object (iteration order is not guaranteed)
+ * // => logs 'a' then 'b' (iteration order is not guaranteed)
*/
- var forEach = createForEach(arrayEach, baseEach);
+ function forEach(collection, iteratee) {
+ return (typeof iteratee == 'function' && isArray(collection))
+ ? arrayEach(collection, iteratee)
+ : baseEach(collection, baseCastFunction(iteratee));
+ }
/**
* This method is like `_.forEach` except that it iterates over elements of
* @memberOf _
* @alias eachRight
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
- * @returns {Array|Object|string} Returns `collection`.
+ * @returns {Array|Object} Returns `collection`.
* @example
*
- * _([1, 2]).forEachRight(function(n) {
- * console.log(n);
- * }).value();
- * // => logs each value from right to left and returns the array
+ * _.forEachRight([1, 2], function(value) {
+ * console.log(value);
+ * });
+ * // => logs `2` then `1`
*/
- var forEachRight = createForEach(arrayEachRight, baseEachRight);
+ function forEachRight(collection, iteratee) {
+ return (typeof iteratee == 'function' && isArray(collection))
+ ? arrayEachRight(collection, iteratee)
+ : baseEachRight(collection, baseCastFunction(iteratee));
+ }
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
- * of each key is an array of the elements responsible for generating the key.
- * The `iteratee` is bound to `thisArg` and invoked with three arguments:
- * (value, index|key, collection).
- *
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * of each key is an array of elements responsible for generating the key.
+ * The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
- * _.groupBy([4.2, 6.1, 6.4], function(n) {
- * return Math.floor(n);
- * });
- * // => { '4': [4.2], '6': [6.1, 6.4] }
+ * _.groupBy([6.1, 4.2, 6.3], Math.floor);
+ * // => { '4': [4.2], '6': [6.1, 6.3] }
*
- * _.groupBy([4.2, 6.1, 6.4], function(n) {
- * return this.floor(n);
- * }, Math);
- * // => { '4': [4.2], '6': [6.1, 6.4] }
- *
- * // using the `_.property` callback shorthand
+ * // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
});
/**
- * Checks if `target` is in `collection` using
- * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
- * for equality comparisons. If `fromIndex` is negative, it's used as the offset
- * from the end of `collection`.
+ * Checks if `value` is in `collection`. If `collection` is a string it's checked
+ * for a substring of `value`, otherwise [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * is used for equality comparisons. If `fromIndex` is negative, it's used as
+ * the offset from the end of `collection`.
*
* @static
* @memberOf _
- * @alias contains, include
* @category Collection
* @param {Array|Object|string} collection The collection to search.
- * @param {*} target The value to search for.
+ * @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
- * @returns {boolean} Returns `true` if a matching element is found, else `false`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.reduce`.
+ * @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* _.includes('pebbles', 'eb');
* // => true
*/
- function includes(collection, target, fromIndex, guard) {
- var length = collection ? getLength(collection) : 0;
- if (!isLength(length)) {
- collection = values(collection);
- length = collection.length;
- }
- if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
- fromIndex = 0;
- } else {
- fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
+ function includes(collection, value, fromIndex, guard) {
+ collection = isArrayLike(collection) ? collection : values(collection);
+ fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
+
+ var length = collection.length;
+ if (fromIndex < 0) {
+ fromIndex = nativeMax(length + fromIndex, 0);
}
- return (typeof collection == 'string' || !isArray(collection) && isString(collection))
- ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
- : (!!length && getIndexOf(collection, target, fromIndex) > -1);
+ return isString(collection)
+ ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
+ : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
/**
- * Creates an object composed of keys generated from the results of running
- * each element of `collection` through `iteratee`. The corresponding value
- * of each key is the last element responsible for generating the key. The
- * iteratee function is bound to `thisArg` and invoked with three arguments:
- * (value, index|key, collection).
- *
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
- *
- * @static
- * @memberOf _
- * @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
- * @returns {Object} Returns the composed aggregate object.
- * @example
- *
- * var keyData = [
- * { 'dir': 'left', 'code': 97 },
- * { 'dir': 'right', 'code': 100 }
- * ];
- *
- * _.indexBy(keyData, 'dir');
- * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
- *
- * _.indexBy(keyData, function(object) {
- * return String.fromCharCode(object.code);
- * });
- * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
- *
- * _.indexBy(keyData, function(object) {
- * return this.fromCharCode(object.code);
- * }, String);
- * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
- */
- var indexBy = createAggregator(function(result, value, key) {
- result[key] = value;
- });
-
- /**
* Invokes the method at `path` of each element in `collection`, returning
* an array of the results of each invoked method. Any additional arguments
* are provided to each invoked method. If `methodName` is a function it's
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Array|Function|string} path The path of the method to invoke or
* the function invoked per iteration.
- * @param {...*} [args] The arguments to invoke the method with.
+ * @param {...*} [args] The arguments to invoke each method with.
* @returns {Array} Returns the array of results.
* @example
*
- * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
+ * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
- * _.invoke([123, 456], String.prototype.split, '');
+ * _.invokeMap([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
- var invoke = restParam(function(collection, path, args) {
+ var invokeMap = rest(function(collection, path, args) {
var index = -1,
isFunc = typeof path == 'function',
isProp = isKey(path),
baseEach(collection, function(value) {
var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
- result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
+ result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args);
});
return result;
});
/**
- * Creates an array of values by running each element in `collection` through
- * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
- * arguments: (value, index|key, collection).
+ * Creates an object composed of keys generated from the results of running
+ * each element of `collection` through `iteratee`. The corresponding value
+ * of each key is the last element responsible for generating the key. The
+ * iteratee is invoked with one argument: (value).
*
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee to transform keys.
+ * @returns {Object} Returns the composed aggregate object.
+ * @example
*
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
+ * var array = [
+ * { 'dir': 'left', 'code': 97 },
+ * { 'dir': 'right', 'code': 100 }
+ * ];
*
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * _.keyBy(array, function(o) {
+ * return String.fromCharCode(o.code);
+ * });
+ * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
+ *
+ * _.keyBy(array, 'dir');
+ * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
+ */
+ var keyBy = createAggregator(function(result, value, key) {
+ result[key] = value;
+ });
+
+ /**
+ * Creates an array of values by running each element in `collection` through
+ * `iteratee`. The iteratee is invoked with three arguments:
+ * (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
- * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
- * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
- * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
- * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
- * `sum`, `uniq`, and `words`
+ * `ary`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, `fill`,
+ * `invert`, `parseInt`, `random`, `range`, `rangeRight`, `slice`, `some`,
+ * `sortBy`, `take`, `takeRight`, `template`, `trim`, `trimEnd`, `trimStart`,
+ * and `words`
*
* @static
* @memberOf _
- * @alias collect
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
- * function timesThree(n) {
- * return n * 3;
+ * function square(n) {
+ * return n * n;
* }
*
- * _.map([1, 2], timesThree);
- * // => [3, 6]
+ * _.map([4, 8], square);
+ * // => [16, 64]
*
- * _.map({ 'a': 1, 'b': 2 }, timesThree);
- * // => [3, 6] (iteration order is not guaranteed)
+ * _.map({ 'a': 4, 'b': 8 }, square);
+ * // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
- * // using the `_.property` callback shorthand
+ * // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
- function map(collection, iteratee, thisArg) {
+ function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
- iteratee = getCallback(iteratee, thisArg, 3);
- return func(collection, iteratee);
+ return func(collection, getIteratee(iteratee, 3));
}
/**
- * Creates an array of elements split into two groups, the first of which
- * contains elements `predicate` returns truthy for, while the second of which
- * contains elements `predicate` returns falsey for. The predicate is bound
- * to `thisArg` and invoked with three arguments: (value, index|key, collection).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * This method is like `_.sortBy` except that it allows specifying the sort
+ * orders of the iteratees to sort by. If `orders` is unspecified, all values
+ * are sorted in ascending order. Otherwise, specify an order of "desc" for
+ * descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
- * @returns {Array} Returns the array of grouped elements.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function[]|Object[]|string[]} [iteratees=[_.identity]] The iteratees to sort by.
+ * @param {string[]} [orders] The sort orders of `iteratees`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.reduce`.
+ * @returns {Array} Returns the new sorted array.
* @example
*
- * _.partition([1, 2, 3], function(n) {
- * return n % 2;
- * });
- * // => [[1, 3], [2]]
- *
- * _.partition([1.2, 2.3, 3.4], function(n) {
- * return this.floor(n) % 2;
- * }, Math);
- * // => [[1.2, 3.4], [2.3]]
- *
* var users = [
- * { 'user': 'barney', 'age': 36, 'active': false },
- * { 'user': 'fred', 'age': 40, 'active': true },
- * { 'user': 'pebbles', 'age': 1, 'active': false }
+ * { 'user': 'fred', 'age': 48 },
+ * { 'user': 'barney', 'age': 34 },
+ * { 'user': 'fred', 'age': 42 },
+ * { 'user': 'barney', 'age': 36 }
* ];
*
- * var mapper = function(array) {
- * return _.pluck(array, 'user');
- * };
- *
- * // using the `_.matches` callback shorthand
- * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
- * // => [['pebbles'], ['barney', 'fred']]
- *
- * // using the `_.matchesProperty` callback shorthand
- * _.map(_.partition(users, 'active', false), mapper);
- * // => [['barney', 'pebbles'], ['fred']]
- *
- * // using the `_.property` callback shorthand
- * _.map(_.partition(users, 'active'), mapper);
- * // => [['fred'], ['barney', 'pebbles']]
+ * // Sort by `user` in ascending order and by `age` in descending order.
+ * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
+ * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
*/
- var partition = createAggregator(function(result, value, key) {
- result[key ? 0 : 1].push(value);
- }, function() { return [[], []]; });
+ function orderBy(collection, iteratees, orders, guard) {
+ if (collection == null) {
+ return [];
+ }
+ if (!isArray(iteratees)) {
+ iteratees = iteratees == null ? [] : [iteratees];
+ }
+ orders = guard ? undefined : orders;
+ if (!isArray(orders)) {
+ orders = orders == null ? [] : [orders];
+ }
+ return baseOrderBy(collection, iteratees, orders);
+ }
/**
- * Gets the property value of `path` from all elements in `collection`.
+ * Creates an array of elements split into two groups, the first of which
+ * contains elements `predicate` returns truthy for, the second of which
+ * contains elements `predicate` returns falsey for. The predicate is
+ * invoked with one argument: (value).
*
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Array|string} path The path of the property to pluck.
- * @returns {Array} Returns the property values.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
+ * @returns {Array} Returns the array of grouped elements.
* @example
*
* var users = [
- * { 'user': 'barney', 'age': 36 },
- * { 'user': 'fred', 'age': 40 }
+ * { 'user': 'barney', 'age': 36, 'active': false },
+ * { 'user': 'fred', 'age': 40, 'active': true },
+ * { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
- * _.pluck(users, 'user');
- * // => ['barney', 'fred']
+ * _.partition(users, function(o) { return o.active; });
+ * // => objects for [['fred'], ['barney', 'pebbles']]
*
- * var userIndex = _.indexBy(users, 'user');
- * _.pluck(userIndex, 'age');
- * // => [36, 40] (iteration order is not guaranteed)
+ * // The `_.matches` iteratee shorthand.
+ * _.partition(users, { 'age': 1, 'active': false });
+ * // => objects for [['pebbles'], ['barney', 'fred']]
+ *
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.partition(users, ['active', false]);
+ * // => objects for [['barney', 'pebbles'], ['fred']]
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.partition(users, 'active');
+ * // => objects for [['fred'], ['barney', 'pebbles']]
*/
- function pluck(collection, path) {
- return map(collection, property(path));
- }
+ var partition = createAggregator(function(result, value, key) {
+ result[key ? 0 : 1].push(value);
+ }, function() { return [[], []]; });
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` through `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
- * is not provided the first element of `collection` is used as the initial
- * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
+ * is not given the first element of `collection` is used as the initial
+ * value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
- * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
- * and `sortByOrder`
+ * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
+ * and `sortBy`
*
* @static
* @memberOf _
- * @alias foldl, inject
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
- * _.reduce([1, 2], function(total, n) {
- * return total + n;
- * });
+ * _.reduce([1, 2], function(sum, n) {
+ * return sum + n;
+ * }, 0);
* // => 3
*
- * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
- * result[key] = n * 3;
+ * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
+ * (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
- * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
+ * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
- var reduce = createReduce(arrayReduce, baseEach);
+ function reduce(collection, iteratee, accumulator) {
+ var func = isArray(collection) ? arrayReduce : baseReduce,
+ initAccum = arguments.length < 3;
+
+ return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
+ }
/**
* This method is like `_.reduce` except that it iterates over elements of
*
* @static
* @memberOf _
- * @alias foldr
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
- var reduceRight = createReduce(arrayReduceRight, baseEachRight);
+ function reduceRight(collection, iteratee, accumulator) {
+ var func = isArray(collection) ? arrayReduceRight : baseReduce,
+ initAccum = arguments.length < 3;
+
+ return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
+ }
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @example
*
- * _.reject([1, 2, 3, 4], function(n) {
- * return n % 2 == 0;
- * });
- * // => [1, 3]
- *
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
- * // using the `_.matches` callback shorthand
- * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
- * // => ['barney']
+ * _.reject(users, function(o) { return !o.active; });
+ * // => objects for ['fred']
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.reject(users, { 'age': 40, 'active': true });
+ * // => objects for ['barney']
*
- * // using the `_.matchesProperty` callback shorthand
- * _.pluck(_.reject(users, 'active', false), 'user');
- * // => ['fred']
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.reject(users, ['active', false]);
+ * // => objects for ['fred']
*
- * // using the `_.property` callback shorthand
- * _.pluck(_.reject(users, 'active'), 'user');
- * // => ['barney']
+ * // The `_.property` iteratee shorthand.
+ * _.reject(users, 'active');
+ * // => objects for ['barney']
*/
- function reject(collection, predicate, thisArg) {
+ function reject(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
- predicate = getCallback(predicate, thisArg, 3);
+ predicate = getIteratee(predicate, 3);
return func(collection, function(value, index, collection) {
return !predicate(value, index, collection);
});
}
/**
- * Gets a random element or `n` random elements from a collection.
+ * Gets a random element from `collection`.
*
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to sample.
- * @param {number} [n] The number of elements to sample.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
- * @returns {*} Returns the random sample(s).
+ * @param {Array|Object} collection The collection to sample.
+ * @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
+ */
+ function sample(collection) {
+ var array = isArrayLike(collection) ? collection : values(collection),
+ length = array.length;
+
+ return length > 0 ? array[baseRandom(0, length - 1)] : undefined;
+ }
+
+ /**
+ * Gets `n` random elements at unique keys from `collection` up to the
+ * size of `collection`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object} collection The collection to sample.
+ * @param {number} [n=0] The number of elements to sample.
+ * @returns {Array} Returns the random elements.
+ * @example
*
- * _.sample([1, 2, 3, 4], 2);
+ * _.sampleSize([1, 2, 3], 2);
* // => [3, 1]
+ *
+ * _.sampleSize([1, 2, 3], 4);
+ * // => [2, 3, 1]
*/
- function sample(collection, n, guard) {
- if (guard ? isIterateeCall(collection, n, guard) : n == null) {
- collection = toIterable(collection);
- var length = collection.length;
- return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
- }
+ function sampleSize(collection, n) {
var index = -1,
result = toArray(collection),
length = result.length,
lastIndex = length - 1;
- n = nativeMin(n < 0 ? 0 : (+n || 0), length);
+ n = baseClamp(toInteger(n), 0, length);
while (++index < n) {
var rand = baseRandom(index, lastIndex),
value = result[rand];
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to shuffle.
+ * @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
- return sample(collection, POSITIVE_INFINITY);
+ return sampleSize(collection, MAX_ARRAY_LENGTH);
}
/**
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to inspect.
- * @returns {number} Returns the size of `collection`.
+ * @param {Array|Object} collection The collection to inspect.
+ * @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 7
*/
function size(collection) {
- var length = collection ? getLength(collection) : 0;
- return isLength(length) ? length : keys(collection).length;
+ if (collection == null) {
+ return 0;
+ }
+ if (isArrayLike(collection)) {
+ var result = collection.length;
+ return (result && isString(collection)) ? stringSize(collection) : result;
+ }
+ return keys(collection).length;
}
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
- * The function returns as soon as it finds a passing value and does not iterate
- * over the entire collection. The predicate is bound to `thisArg` and invoked
- * with three arguments: (value, index|key, collection).
- *
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * Iteration is stopped once `predicate` returns truthy. The predicate is
+ * invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
- * @alias any
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
- * @returns {boolean} Returns `true` if any element passes the predicate check,
- * else `false`.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
+ * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* { 'user': 'fred', 'active': false }
* ];
*
- * // using the `_.matches` callback shorthand
+ * // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
- * // using the `_.matchesProperty` callback shorthand
- * _.some(users, 'active', false);
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.some(users, ['active', false]);
* // => true
*
- * // using the `_.property` callback shorthand
+ * // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
- function some(collection, predicate, thisArg) {
+ function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
- if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
+ if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
- if (typeof predicate != 'function' || thisArg !== undefined) {
- predicate = getCallback(predicate, thisArg, 3);
- }
- return func(collection, predicate);
+ return func(collection, getIteratee(predicate, 3));
}
/**
* Creates an array of elements, sorted in ascending order by the results of
- * running each element in a collection through `iteratee`. This method performs
- * a stable sort, that is, it preserves the original sort order of equal elements.
- * The `iteratee` is bound to `thisArg` and invoked with three arguments:
- * (value, index|key, collection).
- *
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * running each element in a collection through each iteratee. This method
+ * performs a stable sort, that is, it preserves the original sort order of
+ * equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
- * @returns {Array} Returns the new sorted array.
- * @example
- *
- * _.sortBy([1, 2, 3], function(n) {
- * return Math.sin(n);
- * });
- * // => [3, 1, 2]
- *
- * _.sortBy([1, 2, 3], function(n) {
- * return this.sin(n);
- * }, Math);
- * // => [3, 1, 2]
- *
- * var users = [
- * { 'user': 'fred' },
- * { 'user': 'pebbles' },
- * { 'user': 'barney' }
- * ];
- *
- * // using the `_.property` callback shorthand
- * _.pluck(_.sortBy(users, 'user'), 'user');
- * // => ['barney', 'fred', 'pebbles']
- */
- function sortBy(collection, iteratee, thisArg) {
- if (collection == null) {
- return [];
- }
- if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
- iteratee = undefined;
- }
- var index = -1;
- iteratee = getCallback(iteratee, thisArg, 3);
-
- var result = baseMap(collection, function(value, key, collection) {
- return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
- });
- return baseSortBy(result, compareAscending);
- }
-
- /**
- * This method is like `_.sortBy` except that it can sort by multiple iteratees
- * or property names.
- *
- * If a property name is provided for an iteratee the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If an object is provided for an iteratee the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
- *
- * @static
- * @memberOf _
- * @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
- * The iteratees to sort by, specified as individual values or arrays of values.
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {...(Function|Function[]|Object|Object[]|string|string[])} [iteratees=[_.identity]]
+ * The iteratees to sort by, specified individually or in arrays.
* @returns {Array} Returns the new sorted array.
* @example
*
* { 'user': 'barney', 'age': 34 }
* ];
*
- * _.map(_.sortByAll(users, ['user', 'age']), _.values);
- * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
+ * _.sortBy(users, function(o) { return o.user; });
+ * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
*
- * _.map(_.sortByAll(users, 'user', function(chr) {
- * return Math.floor(chr.age / 10);
- * }), _.values);
- * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
+ * _.sortBy(users, ['user', 'age']);
+ * // => objects for [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
+ *
+ * _.sortBy(users, 'user', function(o) {
+ * return Math.floor(o.age / 10);
+ * });
+ * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
*/
- var sortByAll = restParam(function(collection, iteratees) {
+ var sortBy = rest(function(collection, iteratees) {
if (collection == null) {
return [];
}
- var guard = iteratees[2];
- if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
+ var length = iteratees.length;
+ if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
+ iteratees = [];
+ } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees.length = 1;
}
- return baseSortByOrder(collection, baseFlatten(iteratees), []);
+ return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
- /**
- * This method is like `_.sortByAll` except that it allows specifying the
- * sort orders of the iteratees to sort by. If `orders` is unspecified, all
- * values are sorted in ascending order. Otherwise, a value is sorted in
- * ascending order if its corresponding order is "asc", and descending if "desc".
- *
- * If a property name is provided for an iteratee the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If an object is provided for an iteratee the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
- *
- * @static
- * @memberOf _
- * @category Collection
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
- * @param {boolean[]} [orders] The sort orders of `iteratees`.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
- * @returns {Array} Returns the new sorted array.
- * @example
- *
- * var users = [
- * { 'user': 'fred', 'age': 48 },
- * { 'user': 'barney', 'age': 34 },
- * { 'user': 'fred', 'age': 42 },
- * { 'user': 'barney', 'age': 36 }
- * ];
- *
- * // sort by `user` in ascending order and by `age` in descending order
- * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
- * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
- */
- function sortByOrder(collection, iteratees, orders, guard) {
- if (collection == null) {
- return [];
- }
- if (guard && isIterateeCall(iteratees, orders, guard)) {
- orders = undefined;
- }
- if (!isArray(iteratees)) {
- iteratees = iteratees == null ? [] : [iteratees];
- }
- if (!isArray(orders)) {
- orders = orders == null ? [] : [orders];
- }
- return baseSortByOrder(collection, iteratees, orders);
- }
-
- /**
- * Performs a deep comparison between each element in `collection` and the
- * source object, returning an array of all elements that have equivalent
- * property values.
- *
- * **Note:** This method supports comparing arrays, booleans, `Date` objects,
- * numbers, `Object` objects, regexes, and strings. Objects are compared by
- * their own, not inherited, enumerable properties. For comparing a single
- * own or inherited property value see `_.matchesProperty`.
- *
- * @static
- * @memberOf _
- * @category Collection
- * @param {Array|Object|string} collection The collection to search.
- * @param {Object} source The object of property values to match.
- * @returns {Array} Returns the new filtered array.
- * @example
- *
- * var users = [
- * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
- * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
- * ];
- *
- * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
- * // => ['barney']
- *
- * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
- * // => ['fred']
- */
- function where(collection, source) {
- return filter(collection, baseMatches(source));
- }
-
/*------------------------------------------------------------------------*/
/**
- * Gets the number of milliseconds that have elapsed since the Unix epoch
- * (1 January 1970 00:00:00 UTC).
+ * Gets the timestamp of the number of milliseconds that have elapsed since
+ * the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
+ * @type {Function}
* @category Date
+ * @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* }, _.now());
* // => logs the number of milliseconds it took for the deferred function to be invoked
*/
- var now = nativeNow || function() {
- return new Date().getTime();
- };
+ var now = Date.now;
/*------------------------------------------------------------------------*/
*/
function after(n, func) {
if (typeof func != 'function') {
- if (typeof n == 'function') {
- var temp = n;
- n = func;
- func = temp;
- } else {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
+ throw new TypeError(FUNC_ERROR_TEXT);
}
- n = nativeIsFinite(n = +n) ? n : 0;
+ n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
/**
- * Creates a function that accepts up to `n` arguments ignoring any
+ * Creates a function that accepts up to `n` arguments, ignoring any
* additional arguments.
*
* @static
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Function} Returns the new function.
* @example
*
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
- if (guard && isIterateeCall(func, n, guard)) {
- n = undefined;
- }
- n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
+ n = guard ? undefined : n;
+ n = (func && n == null) ? func.length : n;
return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
}
* @returns {Function} Returns the new restricted function.
* @example
*
- * jQuery('#add').on('click', _.before(5, addContactToList));
+ * jQuery(element).on('click', _.before(5, addContactToList));
* // => allows adding up to 4 contacts to the list
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
- if (typeof n == 'function') {
- var temp = n;
- n = func;
- func = temp;
- } else {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
+ throw new TypeError(FUNC_ERROR_TEXT);
}
+ n = toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
- * **Note:** Unlike native `Function#bind` this method does not set the "length"
+ * **Note:** Unlike native `Function#bind` this method doesn't set the "length"
* property of bound functions.
*
* @static
* bound('!');
* // => 'hi fred!'
*
- * // using placeholders
+ * // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
- var bind = restParam(function(func, thisArg, partials) {
+ var bind = rest(function(func, thisArg, partials) {
var bitmask = BIND_FLAG;
if (partials.length) {
- var holders = replaceHolders(partials, bind.placeholder);
+ var holders = replaceHolders(partials, getPlaceholder(bind));
bitmask |= PARTIAL_FLAG;
}
return createWrapper(func, bitmask, thisArg, partials, holders);
});
/**
- * Binds methods of an object to the object itself, overwriting the existing
- * method. Method names may be specified as individual arguments or as arrays
- * of method names. If no method names are provided all enumerable function
- * properties, own and inherited, of `object` are bound.
- *
- * **Note:** This method does not set the "length" property of bound functions.
- *
- * @static
- * @memberOf _
- * @category Function
- * @param {Object} object The object to bind and assign the bound methods to.
- * @param {...(string|string[])} [methodNames] The object method names to bind,
- * specified as individual method names or arrays of method names.
- * @returns {Object} Returns `object`.
- * @example
- *
- * var view = {
- * 'label': 'docs',
- * 'onClick': function() {
- * console.log('clicked ' + this.label);
- * }
- * };
- *
- * _.bindAll(view);
- * jQuery('#docs').on('click', view.onClick);
- * // => logs 'clicked docs' when the element is clicked
- */
- var bindAll = restParam(function(object, methodNames) {
- methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
-
- var index = -1,
- length = methodNames.length;
-
- while (++index < length) {
- var key = methodNames[index];
- object[key] = createWrapper(object[key], BIND_FLAG, object);
- }
- return object;
- });
-
- /**
* Creates a function that invokes the method at `object[key]` and prepends
* any additional `_.bindKey` arguments to those provided to the bound function.
*
* @static
* @memberOf _
* @category Function
- * @param {Object} object The object the method belongs to.
+ * @param {Object} object The object to invoke the method on.
* @param {string} key The key of the method.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* bound('!');
* // => 'hiya fred!'
*
- * // using placeholders
+ * // Bound with placeholders.
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
- var bindKey = restParam(function(object, key, partials) {
+ var bindKey = rest(function(object, key, partials) {
var bitmask = BIND_FLAG | BIND_KEY_FLAG;
if (partials.length) {
- var holders = replaceHolders(partials, bindKey.placeholder);
+ var holders = replaceHolders(partials, getPlaceholder(bindKey));
bitmask |= PARTIAL_FLAG;
}
return createWrapper(key, bitmask, object, partials, holders);
});
/**
- * Creates a function that accepts one or more arguments of `func` that when
- * called either invokes `func` returning its result, if all `func` arguments
- * have been provided, or returns a function that accepts one or more of the
- * remaining `func` arguments, and so on. The arity of `func` may be specified
- * if `func.length` is not sufficient.
+ * Creates a function that accepts arguments of `func` and either invokes
+ * `func` returning its result, if at least `arity` number of arguments have
+ * been provided, or returns a function that accepts the remaining `func`
+ * arguments, and so on. The arity of `func` may be specified if `func.length`
+ * is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
- * **Note:** This method does not set the "length" property of curried functions.
+ * **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
- * // using placeholders
+ * // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
- var curry = createCurry(CURRY_FLAG);
+ function curry(func, arity, guard) {
+ arity = guard ? undefined : arity;
+ var result = createWrapper(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
+ result.placeholder = curry.placeholder;
+ return result;
+ }
/**
* This method is like `_.curry` except that arguments are applied to `func`
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
- * **Note:** This method does not set the "length" property of curried functions.
+ * **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
- * // using placeholders
+ * // Curried with placeholders.
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
- var curryRight = createCurry(CURRY_RIGHT_FLAG);
+ function curryRight(func, arity, guard) {
+ arity = guard ? undefined : arity;
+ var result = createWrapper(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
+ result.placeholder = curryRight.placeholder;
+ return result;
+ }
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
- * delayed invocations. Provide an options object to indicate that `func`
- * should be invoked on the leading and/or trailing edge of the `wait` timeout.
- * Subsequent calls to the debounced function return the result of the last
- * `func` invocation.
+ * delayed `func` invocations and a `flush` method to immediately invoke them.
+ * Provide an options object to indicate whether `func` should be invoked on
+ * the leading and/or trailing edge of the `wait` timeout. The `func` is invoked
+ * with the last arguments provided to the debounced function. Subsequent calls
+ * to the debounced function return the result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
- * on the trailing edge of the timeout only if the the debounced function is
+ * on the trailing edge of the timeout only if the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* @returns {Function} Returns the new debounced function.
* @example
*
- * // avoid costly calculations while the window size is in flux
+ * // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
- * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
- * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
+ * // Invoke `sendMail` when clicked, debouncing subsequent calls.
+ * jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
- * // ensure `batchLog` is invoked once after 1 second of debounced calls
+ * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
+ * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
- * jQuery(source).on('message', _.debounce(batchLog, 250, {
- * 'maxWait': 1000
- * }));
+ * jQuery(source).on('message', debounced);
*
- * // cancel a debounced call
- * var todoChanges = _.debounce(batchLog, 1000);
- * Object.observe(models.todo, todoChanges);
- *
- * Object.observe(models, function(changes) {
- * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
- * todoChanges.cancel();
- * }
- * }, ['delete']);
- *
- * // ...at some point `models.todo` is changed
- * models.todo.completed = true;
- *
- * // ...before 1 second has passed `models.todo` is deleted
- * // which cancels the debounced `todoChanges` call
- * delete models.todo;
+ * // Cancel the trailing debounced invocation.
+ * jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var args,
timeoutId,
trailingCall,
lastCalled = 0,
+ leading = false,
maxWait = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
- wait = wait < 0 ? 0 : (+wait || 0);
- if (options === true) {
- var leading = true;
- trailing = false;
- } else if (isObject(options)) {
+ wait = toNumber(wait) || 0;
+ if (isObject(options)) {
leading = !!options.leading;
- maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
+ maxWait = 'maxWait' in options && nativeMax(toNumber(options.maxWait) || 0, wait);
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
clearTimeout(maxTimeoutId);
}
lastCalled = 0;
- maxTimeoutId = timeoutId = trailingCall = undefined;
+ args = maxTimeoutId = thisArg = timeoutId = trailingCall = undefined;
}
function complete(isCalled, id) {
}
}
+ function flush() {
+ if ((timeoutId && trailingCall) || (maxTimeoutId && trailing)) {
+ result = func.apply(thisArg, args);
+ }
+ cancel();
+ return result;
+ }
+
function maxDelayed() {
complete(trailing, timeoutId);
}
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
- if (!maxTimeoutId && !leading) {
+ if (!lastCalled && !maxTimeoutId && !leading) {
lastCalled = stamp;
}
- var remaining = maxWait - (stamp - lastCalled),
- isCalled = remaining <= 0 || remaining > maxWait;
+ var remaining = maxWait - (stamp - lastCalled);
+
+ var isCalled = (remaining <= 0 || remaining > maxWait) &&
+ (leading || maxTimeoutId);
if (isCalled) {
if (maxTimeoutId) {
return result;
}
debounced.cancel = cancel;
+ debounced.flush = flush;
return debounced;
}
* @memberOf _
* @category Function
* @param {Function} func The function to defer.
- * @param {...*} [args] The arguments to invoke the function with.
+ * @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
- * // logs 'deferred' after one or more milliseconds
+ * // => logs 'deferred' after one or more milliseconds
*/
- var defer = restParam(function(func, args) {
+ var defer = rest(function(func, args) {
return baseDelay(func, 1, args);
});
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
- * @param {...*} [args] The arguments to invoke the function with.
+ * @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* }, 1000, 'later');
* // => logs 'later' after one second
*/
- var delay = restParam(function(func, wait, args) {
- return baseDelay(func, wait, args);
+ var delay = rest(function(func, wait, args) {
+ return baseDelay(func, toNumber(wait) || 0, args);
});
/**
- * Creates a function that returns the result of invoking the provided
- * functions with the `this` binding of the created function, where each
- * successive invocation is supplied the return value of the previous.
+ * Creates a function that invokes `func` with arguments reversed.
*
* @static
* @memberOf _
* @category Function
- * @param {...Function} [funcs] Functions to invoke.
+ * @param {Function} func The function to flip arguments for.
* @returns {Function} Returns the new function.
* @example
*
- * function square(n) {
- * return n * n;
- * }
- *
- * var addSquare = _.flow(_.add, square);
- * addSquare(1, 2);
- * // => 9
- */
- var flow = createFlow();
-
- /**
- * This method is like `_.flow` except that it creates a function that
- * invokes the provided functions from right to left.
- *
- * @static
- * @memberOf _
- * @alias backflow, compose
- * @category Function
- * @param {...Function} [funcs] Functions to invoke.
- * @returns {Function} Returns the new function.
- * @example
- *
- * function square(n) {
- * return n * n;
- * }
+ * var flipped = _.flip(function() {
+ * return _.toArray(arguments);
+ * });
*
- * var addSquare = _.flowRight(square, _.add);
- * addSquare(1, 2);
- * // => 9
+ * flipped('a', 'b', 'c', 'd');
+ * // => ['d', 'c', 'b', 'a']
*/
- var flowRight = createFlow(true);
+ function flip(func) {
+ return createWrapper(func, FLIP_FLAG);
+ }
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
- * provided to the memoized function is coerced to a string and used as the
- * cache key. The `func` is invoked with the `this` binding of the memoized
- * function.
+ * provided to the memoized function is used as the map cache key. The `func`
+ * is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
- * method interface of `get`, `has`, and `set`.
+ * method interface of `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @returns {Function} Returns the new memoizing function.
* @example
*
- * var upperCase = _.memoize(function(string) {
- * return string.toUpperCase();
- * });
+ * var object = { 'a': 1, 'b': 2 };
+ * var other = { 'c': 3, 'd': 4 };
*
- * upperCase('fred');
- * // => 'FRED'
+ * var values = _.memoize(_.values);
+ * values(object);
+ * // => [1, 2]
*
- * // modifying the result cache
- * upperCase.cache.set('fred', 'BARNEY');
- * upperCase('fred');
- * // => 'BARNEY'
+ * values(other);
+ * // => [3, 4]
*
- * // replacing `_.memoize.Cache`
- * var object = { 'user': 'fred' };
- * var other = { 'user': 'barney' };
- * var identity = _.memoize(_.identity);
+ * object.a = 2;
+ * values(object);
+ * // => [1, 2]
*
- * identity(object);
- * // => { 'user': 'fred' }
- * identity(other);
- * // => { 'user': 'fred' }
+ * // Modify the result cache.
+ * values.cache.set(object, ['a', 'b']);
+ * values(object);
+ * // => ['a', 'b']
*
+ * // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
- * var identity = _.memoize(_.identity);
- *
- * identity(object);
- * // => { 'user': 'fred' }
- * identity(other);
- * // => { 'user': 'barney' }
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
}
/**
- * Creates a function that runs each argument through a corresponding
- * transform function.
- *
- * @static
- * @memberOf _
- * @category Function
- * @param {Function} func The function to wrap.
- * @param {...(Function|Function[])} [transforms] The functions to transform
- * arguments, specified as individual functions or arrays of functions.
- * @returns {Function} Returns the new function.
- * @example
- *
- * function doubled(n) {
- * return n * 2;
- * }
- *
- * function square(n) {
- * return n * n;
- * }
- *
- * var modded = _.modArgs(function(x, y) {
- * return [x, y];
- * }, square, doubled);
- *
- * modded(1, 2);
- * // => [1, 4]
- *
- * modded(5, 10);
- * // => [25, 20]
- */
- var modArgs = restParam(function(func, transforms) {
- transforms = baseFlatten(transforms);
- if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
- var length = transforms.length;
- return restParam(function(args) {
- var index = nativeMin(args.length, length);
- while (index--) {
- args[index] = transforms[index](args[index]);
- }
- return func.apply(this, args);
- });
- });
-
- /**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
- * to the function return the value of the first call. The `func` is invoked
- * with the `this` binding and arguments of the created function.
+ * to the function return the value of the first invocation. The `func` is
+ * invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
}
/**
+ * Creates a function that invokes `func` with arguments transformed by
+ * corresponding `transforms`.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to wrap.
+ * @param {...(Function|Function[])} [transforms] The functions to transform
+ * arguments, specified individually or in arrays.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * function doubled(n) {
+ * return n * 2;
+ * }
+ *
+ * function square(n) {
+ * return n * n;
+ * }
+ *
+ * var func = _.overArgs(function(x, y) {
+ * return [x, y];
+ * }, square, doubled);
+ *
+ * func(9, 3);
+ * // => [81, 6]
+ *
+ * func(10, 5);
+ * // => [100, 10]
+ */
+ var overArgs = rest(function(func, transforms) {
+ transforms = arrayMap(baseFlatten(transforms, 1), getIteratee());
+
+ var funcsLength = transforms.length;
+ return rest(function(args) {
+ var index = -1,
+ length = nativeMin(args.length, funcsLength);
+
+ while (++index < length) {
+ args[index] = transforms[index].call(this, args[index]);
+ }
+ return apply(func, this, args);
+ });
+ });
+
+ /**
* Creates a function that invokes `func` with `partial` arguments prepended
* to those provided to the new function. This method is like `_.bind` except
* it does **not** alter the `this` binding.
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
- * **Note:** This method does not set the "length" property of partially
+ * **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* sayHelloTo('fred');
* // => 'hello fred'
*
- * // using placeholders
+ * // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
- var partial = createPartial(PARTIAL_FLAG);
+ var partial = rest(function(func, partials) {
+ var holders = replaceHolders(partials, getPlaceholder(partial));
+ return createWrapper(func, PARTIAL_FLAG, undefined, partials, holders);
+ });
/**
* This method is like `_.partial` except that partially applied arguments
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
- * **Note:** This method does not set the "length" property of partially
+ * **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* greetFred('hi');
* // => 'hi fred'
*
- * // using placeholders
+ * // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
- var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
+ var partialRight = rest(function(func, partials) {
+ var holders = replaceHolders(partials, getPlaceholder(partialRight));
+ return createWrapper(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders);
+ });
/**
* Creates a function that invokes `func` with arguments arranged according
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes,
- * specified as individual indexes or arrays of indexes.
+ * specified individually or in arrays.
* @returns {Function} Returns the new function.
* @example
*
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
- *
- * var map = _.rearg(_.map, [1, 0]);
- * map(function(n) {
- * return n * 3;
- * }, [1, 2, 3]);
- * // => [3, 6, 9]
*/
- var rearg = restParam(function(func, indexes) {
- return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
+ var rearg = rest(function(func, indexes) {
+ return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes, 1));
});
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
- * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
+ * **Note:** This method is based on the [rest parameter](https://mdn.io/rest_parameters).
*
* @static
* @memberOf _
* @returns {Function} Returns the new function.
* @example
*
- * var say = _.restParam(function(what, names) {
+ * var say = _.rest(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
- function restParam(func, start) {
+ function rest(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
- start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
+ start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
- rest = Array(length);
+ array = Array(length);
while (++index < length) {
- rest[index] = args[start + index];
+ array[index] = args[start + index];
}
switch (start) {
- case 0: return func.call(this, rest);
- case 1: return func.call(this, args[0], rest);
- case 2: return func.call(this, args[0], args[1], rest);
+ case 0: return func.call(this, array);
+ case 1: return func.call(this, args[0], array);
+ case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
- otherArgs[start] = rest;
- return func.apply(this, otherArgs);
+ otherArgs[start] = array;
+ return apply(func, this, otherArgs);
};
}
* Creates a function that invokes `func` with the `this` binding of the created
* function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
*
- * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/Web/JavaScript/Reference/Operators/Spread_operator).
+ * **Note:** This method is based on the [spread operator](https://mdn.io/spread_operator).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to spread arguments over.
+ * @param {number} [start=0] The start position of the spread.
* @returns {Function} Returns the new function.
* @example
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
- * // with a Promise
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* }));
* // => a Promise of 76
*/
- function spread(func) {
+ function spread(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
- return function(array) {
- return func.apply(this, array);
- };
+ start = start === undefined ? 0 : nativeMax(toInteger(start), 0);
+ return rest(function(args) {
+ var array = args[start],
+ otherArgs = args.slice(0, start);
+
+ if (array) {
+ arrayPush(otherArgs, array);
+ }
+ return apply(func, this, otherArgs);
+ });
}
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
- * method to cancel delayed invocations. Provide an options object to indicate
- * that `func` should be invoked on the leading and/or trailing edge of the
- * `wait` timeout. Subsequent calls to the throttled function return the
- * result of the last `func` call.
+ * method to cancel delayed `func` invocations and a `flush` method to
+ * immediately invoke them. Provide an options object to indicate whether
+ * `func` should be invoked on the leading and/or trailing edge of the `wait`
+ * timeout. The `func` is invoked with the last arguments provided to the
+ * throttled function. Subsequent calls to the throttled function return the
+ * result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
- * on the trailing edge of the timeout only if the the throttled function is
+ * on the trailing edge of the timeout only if the throttled function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* @returns {Function} Returns the new throttled function.
* @example
*
- * // avoid excessively updating the position while scrolling
+ * // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
- * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
- * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
- * 'trailing': false
- * }));
+ * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
+ * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
+ * jQuery(element).on('click', throttled);
*
- * // cancel a trailing throttled call
+ * // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
- if (options === false) {
- leading = false;
- } else if (isObject(options)) {
+ if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
- return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
+ return debounce(func, wait, {
+ 'leading': leading,
+ 'maxWait': wait,
+ 'trailing': trailing
+ });
+ }
+
+ /**
+ * Creates a function that accepts up to one argument, ignoring any
+ * additional arguments.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to cap arguments for.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * _.map(['6', '8', '10'], _.unary(parseInt));
+ * // => [6, 8, 10]
+ */
+ function unary(func) {
+ return ary(func, 1);
}
/**
* @memberOf _
* @category Function
* @param {*} value The value to wrap.
- * @param {Function} wrapper The wrapper function.
+ * @param {Function} [wrapper=identity] The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
*/
function wrap(value, wrapper) {
wrapper = wrapper == null ? identity : wrapper;
- return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
+ return partial(wrapper, value);
}
/*------------------------------------------------------------------------*/
/**
- * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
- * otherwise they are assigned by reference. If `customizer` is provided it's
- * invoked to produce the cloned values. If `customizer` returns `undefined`
- * cloning is handled by the method instead. The `customizer` is bound to
- * `thisArg` and invoked with up to three argument; (value [, index|key, object]).
+ * Casts `value` as an array if it's not one.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to inspect.
+ * @returns {Array} Returns the cast array.
+ * @example
+ *
+ * _.castArray(1);
+ * // => [1]
+ *
+ * _.castArray({ 'a': 1 });
+ * // => [{ 'a': 1 }]
+ *
+ * _.castArray('abc');
+ * // => ['abc']
+ *
+ * _.castArray(null);
+ * // => [null]
+ *
+ * _.castArray(undefined);
+ * // => [undefined]
+ *
+ * _.castArray();
+ * // => []
+ *
+ * var array = [1, 2, 3];
+ * console.log(_.castArray(array) === array);
+ * // => true
+ */
+ function castArray() {
+ if (!arguments.length) {
+ return [];
+ }
+ var value = arguments[0];
+ return isArray(value) ? value : [value];
+ }
+
+ /**
+ * Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
- * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
- * The enumerable properties of `arguments` objects and objects created by
- * constructors other than `Object` are cloned to plain `Object` objects. An
- * empty object is returned for uncloneable values such as functions, DOM nodes,
- * Maps, Sets, and WeakMaps.
+ * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
+ * and supports cloning arrays, array buffers, booleans, date objects, maps,
+ * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
+ * arrays. The own enumerable properties of `arguments` objects are cloned
+ * as plain objects. An empty object is returned for uncloneable values such
+ * as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to clone.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @param {Function} [customizer] The function to customize cloning values.
- * @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {*} Returns the cloned value.
* @example
*
- * var users = [
- * { 'user': 'barney' },
- * { 'user': 'fred' }
- * ];
+ * var objects = [{ 'a': 1 }, { 'b': 2 }];
*
- * var shallow = _.clone(users);
- * shallow[0] === users[0];
+ * var shallow = _.clone(objects);
+ * console.log(shallow[0] === objects[0]);
* // => true
+ */
+ function clone(value) {
+ return baseClone(value);
+ }
+
+ /**
+ * This method is like `_.clone` except that it accepts `customizer` which
+ * is invoked to produce the cloned value. If `customizer` returns `undefined`
+ * cloning is handled by the method instead. The `customizer` is invoked with
+ * up to four arguments; (value [, index|key, object, stack]).
*
- * var deep = _.clone(users, true);
- * deep[0] === users[0];
- * // => false
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to clone.
+ * @param {Function} [customizer] The function to customize cloning.
+ * @returns {*} Returns the cloned value.
+ * @example
*
- * // using a customizer callback
- * var el = _.clone(document.body, function(value) {
+ * function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
- * });
+ * }
*
- * el === document.body
+ * var el = _.cloneWith(document.body, customizer);
+ *
+ * console.log(el === document.body);
* // => false
- * el.nodeName
- * // => BODY
- * el.childNodes.length;
+ * console.log(el.nodeName);
+ * // => 'BODY'
+ * console.log(el.childNodes.length);
* // => 0
*/
- function clone(value, isDeep, customizer, thisArg) {
- if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
- isDeep = false;
- }
- else if (typeof isDeep == 'function') {
- thisArg = customizer;
- customizer = isDeep;
- isDeep = false;
- }
- return typeof customizer == 'function'
- ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 3))
- : baseClone(value, isDeep);
+ function cloneWith(value, customizer) {
+ return baseClone(value, false, customizer);
}
/**
- * Creates a deep clone of `value`. If `customizer` is provided it's invoked
- * to produce the cloned values. If `customizer` returns `undefined` cloning
- * is handled by the method instead. The `customizer` is bound to `thisArg`
- * and invoked with up to three argument; (value [, index|key, object]).
- *
- * **Note:** This method is loosely based on the
- * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
- * The enumerable properties of `arguments` objects and objects created by
- * constructors other than `Object` are cloned to plain `Object` objects. An
- * empty object is returned for uncloneable values such as functions, DOM nodes,
- * Maps, Sets, and WeakMaps.
+ * This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @category Lang
- * @param {*} value The value to deep clone.
- * @param {Function} [customizer] The function to customize cloning values.
- * @param {*} [thisArg] The `this` binding of `customizer`.
+ * @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @example
*
- * var users = [
- * { 'user': 'barney' },
- * { 'user': 'fred' }
- * ];
+ * var objects = [{ 'a': 1 }, { 'b': 2 }];
*
- * var deep = _.cloneDeep(users);
- * deep[0] === users[0];
+ * var deep = _.cloneDeep(objects);
+ * console.log(deep[0] === objects[0]);
* // => false
+ */
+ function cloneDeep(value) {
+ return baseClone(value, true);
+ }
+
+ /**
+ * This method is like `_.cloneWith` except that it recursively clones `value`.
*
- * // using a customizer callback
- * var el = _.cloneDeep(document.body, function(value) {
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to recursively clone.
+ * @param {Function} [customizer] The function to customize cloning.
+ * @returns {*} Returns the deep cloned value.
+ * @example
+ *
+ * function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
- * });
+ * }
*
- * el === document.body
+ * var el = _.cloneDeepWith(document.body, customizer);
+ *
+ * console.log(el === document.body);
* // => false
- * el.nodeName
- * // => BODY
- * el.childNodes.length;
+ * console.log(el.nodeName);
+ * // => 'BODY'
+ * console.log(el.childNodes.length);
* // => 20
*/
- function cloneDeep(value, customizer, thisArg) {
- return typeof customizer == 'function'
- ? baseClone(value, true, bindCallback(customizer, thisArg, 3))
- : baseClone(value, true);
+ function cloneDeepWith(value, customizer) {
+ return baseClone(value, true, customizer);
+ }
+
+ /**
+ * Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * comparison between two values to determine if they are equivalent.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ * @example
+ *
+ * var object = { 'user': 'fred' };
+ * var other = { 'user': 'fred' };
+ *
+ * _.eq(object, object);
+ * // => true
+ *
+ * _.eq(object, other);
+ * // => false
+ *
+ * _.eq('a', 'a');
+ * // => true
+ *
+ * _.eq('a', Object('a'));
+ * // => false
+ *
+ * _.eq(NaN, NaN);
+ * // => true
+ */
+ function eq(value, other) {
+ return value === other || (value !== value && other !== other);
}
/**
}
/**
- * Checks if `value` is classified as an `arguments` object.
+ * Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* // => false
*/
function isArguments(value) {
- return isObjectLike(value) && isArrayLike(value) &&
- hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
+ // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
+ return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
+ (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
*
* @static
* @memberOf _
+ * @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* _.isArray([1, 2, 3]);
* // => true
*
- * _.isArray(function() { return arguments; }());
+ * _.isArray(document.body.children);
+ * // => false
+ *
+ * _.isArray('abc');
+ * // => false
+ *
+ * _.isArray(_.noop);
* // => false
*/
- var isArray = nativeIsArray || function(value) {
- return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
- };
+ var isArray = Array.isArray;
+
+ /**
+ * Checks if `value` is classified as an `ArrayBuffer` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isArrayBuffer(new ArrayBuffer(2));
+ * // => true
+ *
+ * _.isArrayBuffer(new Array(2));
+ * // => false
+ */
+ function isArrayBuffer(value) {
+ return isObjectLike(value) && objectToString.call(value) == arrayBufferTag;
+ }
+
+ /**
+ * Checks if `value` is array-like. A value is considered array-like if it's
+ * not a function and has a `value.length` that's an integer greater than or
+ * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
+ * @example
+ *
+ * _.isArrayLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isArrayLike(document.body.children);
+ * // => true
+ *
+ * _.isArrayLike('abc');
+ * // => true
+ *
+ * _.isArrayLike(_.noop);
+ * // => false
+ */
+ function isArrayLike(value) {
+ return value != null &&
+ !(typeof value == 'function' && isFunction(value)) && isLength(getLength(value));
+ }
+
+ /**
+ * This method is like `_.isArrayLike` except that it also checks if `value`
+ * is an object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`.
+ * @example
+ *
+ * _.isArrayLikeObject([1, 2, 3]);
+ * // => true
+ *
+ * _.isArrayLikeObject(document.body.children);
+ * // => true
+ *
+ * _.isArrayLikeObject('abc');
+ * // => false
+ *
+ * _.isArrayLikeObject(_.noop);
+ * // => false
+ */
+ function isArrayLikeObject(value) {
+ return isObjectLike(value) && isArrayLike(value);
+ }
/**
* Checks if `value` is classified as a boolean primitive or object.
* // => false
*/
function isBoolean(value) {
- return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
+ return value === true || value === false ||
+ (isObjectLike(value) && objectToString.call(value) == boolTag);
}
/**
+ * Checks if `value` is a buffer.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
+ * @example
+ *
+ * _.isBuffer(new Buffer(2));
+ * // => true
+ *
+ * _.isBuffer(new Uint8Array(2));
+ * // => false
+ */
+ var isBuffer = !Buffer ? constant(false) : function(value) {
+ return value instanceof Buffer;
+ };
+
+ /**
* Checks if `value` is classified as a `Date` object.
*
* @static
* // => false
*/
function isDate(value) {
- return isObjectLike(value) && objToString.call(value) == dateTag;
+ return isObjectLike(value) && objectToString.call(value) == dateTag;
}
/**
- * Checks if `value` is a DOM element.
+ * Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* // => false
*/
function isEmpty(value) {
- if (value == null) {
- return true;
- }
- if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
- (isObjectLike(value) && isFunction(value.splice)))) {
+ if (isArrayLike(value) &&
+ (isArray(value) || isString(value) ||
+ isFunction(value.splice) || isArguments(value))) {
return !value.length;
}
- return !keys(value).length;
+ for (var key in value) {
+ if (hasOwnProperty.call(value, key)) {
+ return false;
+ }
+ }
+ return true;
}
/**
* Performs a deep comparison between two values to determine if they are
- * equivalent. If `customizer` is provided it's invoked to compare values.
- * If `customizer` returns `undefined` comparisons are handled by the method
- * instead. The `customizer` is bound to `thisArg` and invoked with up to
- * three arguments: (value, other [, index|key]).
+ * equivalent.
*
- * **Note:** This method supports comparing arrays, booleans, `Date` objects,
- * numbers, `Object` objects, regexes, and strings. Objects are compared by
- * their own, not inherited, enumerable properties. Functions and DOM nodes
- * are **not** supported. Provide a customizer function to extend support
- * for comparing other values.
+ * **Note:** This method supports comparing arrays, array buffers, booleans,
+ * date objects, error objects, maps, numbers, `Object` objects, regexes,
+ * sets, strings, symbols, and typed arrays. `Object` objects are compared
+ * by their own, not inherited, enumerable properties. Functions and DOM
+ * nodes are **not** supported.
*
* @static
* @memberOf _
- * @alias eq
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
- * @param {Function} [customizer] The function to customize value comparisons.
- * @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
- * object == other;
- * // => false
- *
* _.isEqual(object, other);
* // => true
*
- * // using a customizer callback
- * var array = ['hello', 'goodbye'];
- * var other = ['hi', 'goodbye'];
+ * object === other;
+ * // => false
+ */
+ function isEqual(value, other) {
+ return baseIsEqual(value, other);
+ }
+
+ /**
+ * This method is like `_.isEqual` except that it accepts `customizer` which
+ * is invoked to compare values. If `customizer` returns `undefined` comparisons
+ * are handled by the method instead. The `customizer` is invoked with up to
+ * six arguments: (objValue, othValue [, index|key, object, other, stack]).
*
- * _.isEqual(array, other, function(value, other) {
- * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ * @example
+ *
+ * function isGreeting(value) {
+ * return /^h(?:i|ello)$/.test(value);
+ * }
+ *
+ * function customizer(objValue, othValue) {
+ * if (isGreeting(objValue) && isGreeting(othValue)) {
* return true;
* }
- * });
+ * }
+ *
+ * var array = ['hello', 'goodbye'];
+ * var other = ['hi', 'goodbye'];
+ *
+ * _.isEqualWith(array, other, customizer);
* // => true
*/
- function isEqual(value, other, customizer, thisArg) {
- customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
+ function isEqualWith(value, other, customizer) {
+ customizer = typeof customizer == 'function' ? customizer : undefined;
var result = customizer ? customizer(value, other) : undefined;
- return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
+ return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
}
/**
* // => false
*/
function isError(value) {
- return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
+ if (!isObjectLike(value)) {
+ return false;
+ }
+ return (objectToString.call(value) == errorTag) ||
+ (typeof value.message == 'string' && typeof value.name == 'string');
}
/**
* Checks if `value` is a finite primitive number.
*
- * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite).
+ * **Note:** This method is based on [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
- * _.isFinite(10);
+ * _.isFinite(3);
* // => true
*
- * _.isFinite('10');
- * // => false
- *
- * _.isFinite(true);
- * // => false
+ * _.isFinite(Number.MAX_VALUE);
+ * // => true
*
- * _.isFinite(Object(10));
- * // => false
+ * _.isFinite(3.14);
+ * // => true
*
* _.isFinite(Infinity);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
- // in older versions of Chrome and Safari which return 'function' for regexes
- // and Safari 8 which returns 'object' for typed array constructors.
- return isObject(value) && objToString.call(value) == funcTag;
+ // in Safari 8 which returns 'object' for typed array constructors, and
+ // PhantomJS 1.9 which returns 'function' for `NodeList` instances.
+ var tag = isObject(value) ? objectToString.call(value) : '';
+ return tag == funcTag || tag == genTag;
+ }
+
+ /**
+ * Checks if `value` is an integer.
+ *
+ * **Note:** This method is based on [`Number.isInteger`](https://mdn.io/Number/isInteger).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
+ * @example
+ *
+ * _.isInteger(3);
+ * // => true
+ *
+ * _.isInteger(Number.MIN_VALUE);
+ * // => false
+ *
+ * _.isInteger(Infinity);
+ * // => false
+ *
+ * _.isInteger('3');
+ * // => false
+ */
+ function isInteger(value) {
+ return typeof value == 'number' && value == toInteger(value);
+ }
+
+ /**
+ * Checks if `value` is a valid array-like length.
+ *
+ * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
+ * @example
+ *
+ * _.isLength(3);
+ * // => true
+ *
+ * _.isLength(Number.MIN_VALUE);
+ * // => false
+ *
+ * _.isLength(Infinity);
+ * // => false
+ *
+ * _.isLength('3');
+ * // => false
+ */
+ function isLength(value) {
+ return typeof value == 'number' &&
+ value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* _.isObject([1, 2, 3]);
* // => true
*
- * _.isObject(1);
+ * _.isObject(_.noop);
+ * // => true
+ *
+ * _.isObject(null);
* // => false
*/
function isObject(value) {
- // Avoid a V8 JIT bug in Chrome 19-20.
- // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
- * Performs a deep comparison between `object` and `source` to determine if
- * `object` contains equivalent property values. If `customizer` is provided
- * it's invoked to compare values. If `customizer` returns `undefined`
- * comparisons are handled by the method instead. The `customizer` is bound
- * to `thisArg` and invoked with three arguments: (value, other, index|key).
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
+ * and has a `typeof` result of "object".
*
- * **Note:** This method supports comparing properties of arrays, booleans,
- * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
- * and DOM nodes are **not** supported. Provide a customizer function to extend
- * support for comparing other values.
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
+ * @example
+ *
+ * _.isObjectLike({});
+ * // => true
+ *
+ * _.isObjectLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isObjectLike(_.noop);
+ * // => false
+ *
+ * _.isObjectLike(null);
+ * // => false
+ */
+ function isObjectLike(value) {
+ return !!value && typeof value == 'object';
+ }
+
+ /**
+ * Checks if `value` is classified as a `Map` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isMap(new Map);
+ * // => true
+ *
+ * _.isMap(new WeakMap);
+ * // => false
+ */
+ function isMap(value) {
+ return isObjectLike(value) && getTag(value) == mapTag;
+ }
+
+ /**
+ * Performs a partial deep comparison between `object` and `source` to
+ * determine if `object` contains equivalent property values. This method is
+ * equivalent to a `_.matches` function when `source` is partially applied.
+ *
+ * **Note:** This method supports comparing the same values as `_.isEqual`.
*
* @static
* @memberOf _
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
- * @param {Function} [customizer] The function to customize value comparisons.
- * @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
*
* _.isMatch(object, { 'age': 36 });
* // => false
+ */
+ function isMatch(object, source) {
+ return object === source || baseIsMatch(object, source, getMatchData(source));
+ }
+
+ /**
+ * This method is like `_.isMatch` except that it accepts `customizer` which
+ * is invoked to compare values. If `customizer` returns `undefined` comparisons
+ * are handled by the method instead. The `customizer` is invoked with five
+ * arguments: (objValue, srcValue, index|key, object, source).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {Object} object The object to inspect.
+ * @param {Object} source The object of property values to match.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @returns {boolean} Returns `true` if `object` is a match, else `false`.
+ * @example
+ *
+ * function isGreeting(value) {
+ * return /^h(?:i|ello)$/.test(value);
+ * }
+ *
+ * function customizer(objValue, srcValue) {
+ * if (isGreeting(objValue) && isGreeting(srcValue)) {
+ * return true;
+ * }
+ * }
*
- * // using a customizer callback
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
- * _.isMatch(object, source, function(value, other) {
- * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
- * });
+ * _.isMatchWith(object, source, customizer);
* // => true
*/
- function isMatch(object, source, customizer, thisArg) {
- customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
- return baseIsMatch(object, getMatchData(source), customizer);
+ function isMatchWith(object, source, customizer) {
+ customizer = typeof customizer == 'function' ? customizer : undefined;
+ return baseIsMatch(object, source, getMatchData(source), customizer);
}
/**
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
- // Perform the `toStringTag` check first to avoid errors with some host objects in IE.
+ // Perform the `toStringTag` check first to avoid errors with some ActiveX objects in IE.
return isNumber(value) && value != +value;
}
return false;
}
if (isFunction(value)) {
- return reIsNative.test(fnToString.call(value));
+ return reIsNative.test(funcToString.call(value));
}
- return isObjectLike(value) && reIsHostCtor.test(value);
+ return isObjectLike(value) &&
+ (isHostObject(value) ? reIsNative : reIsHostCtor).test(value);
}
/**
}
/**
+ * Checks if `value` is `null` or `undefined`.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
+ * @example
+ *
+ * _.isNil(null);
+ * // => true
+ *
+ * _.isNil(void 0);
+ * // => true
+ *
+ * _.isNil(NaN);
+ * // => false
+ */
+ function isNil(value) {
+ return value == null;
+ }
+
+ /**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
- * _.isNumber(8.4);
+ * _.isNumber(3);
* // => true
*
- * _.isNumber(NaN);
+ * _.isNumber(Number.MIN_VALUE);
* // => true
*
- * _.isNumber('8.4');
+ * _.isNumber(Infinity);
+ * // => true
+ *
+ * _.isNumber('3');
* // => false
*/
function isNumber(value) {
- return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
+ return typeof value == 'number' ||
+ (isObjectLike(value) && objectToString.call(value) == numberTag);
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
- * **Note:** This method assumes objects created by the `Object` constructor
- * have no inherited enumerable properties.
- *
* @static
* @memberOf _
* @category Lang
* // => true
*/
function isPlainObject(value) {
- var Ctor;
-
- // Exit early for non `Object` objects.
- if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
- (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
+ if (!isObjectLike(value) ||
+ objectToString.call(value) != objectTag || isHostObject(value)) {
return false;
}
- // IE < 9 iterates inherited properties before own properties. If the first
- // iterated property is an object's own property then there are no inherited
- // enumerable properties.
- var result;
- // In most environments an object's own properties are iterated before
- // its inherited properties. If the last iterated property is an object's
- // own property then there are no inherited enumerable properties.
- baseForIn(value, function(subValue, key) {
- result = key;
- });
- return result === undefined || hasOwnProperty.call(value, result);
+ var proto = getPrototypeOf(value);
+ if (proto === null) {
+ return true;
+ }
+ var Ctor = proto.constructor;
+ return (typeof Ctor == 'function' &&
+ Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}
/**
* // => false
*/
function isRegExp(value) {
- return isObject(value) && objToString.call(value) == regexpTag;
+ return isObject(value) && objectToString.call(value) == regexpTag;
+ }
+
+ /**
+ * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
+ * double precision number which isn't the result of a rounded unsafe integer.
+ *
+ * **Note:** This method is based on [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
+ * @example
+ *
+ * _.isSafeInteger(3);
+ * // => true
+ *
+ * _.isSafeInteger(Number.MIN_VALUE);
+ * // => false
+ *
+ * _.isSafeInteger(Infinity);
+ * // => false
+ *
+ * _.isSafeInteger('3');
+ * // => false
+ */
+ function isSafeInteger(value) {
+ return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
+ }
+
+ /**
+ * Checks if `value` is classified as a `Set` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isSet(new Set);
+ * // => true
+ *
+ * _.isSet(new WeakSet);
+ * // => false
+ */
+ function isSet(value) {
+ return isObjectLike(value) && getTag(value) == setTag;
}
/**
* // => false
*/
function isString(value) {
- return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
+ return typeof value == 'string' ||
+ (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
+ }
+
+ /**
+ * Checks if `value` is classified as a `Symbol` primitive or object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isSymbol(Symbol.iterator);
+ * // => true
+ *
+ * _.isSymbol('abc');
+ * // => false
+ */
+ function isSymbol(value) {
+ return typeof value == 'symbol' ||
+ (isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* // => false
*/
function isTypedArray(value) {
- return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
+ return isObjectLike(value) &&
+ isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
}
/**
}
/**
+ * Checks if `value` is classified as a `WeakMap` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isWeakMap(new WeakMap);
+ * // => true
+ *
+ * _.isWeakMap(new Map);
+ * // => false
+ */
+ function isWeakMap(value) {
+ return isObjectLike(value) && getTag(value) == weakMapTag;
+ }
+
+ /**
+ * Checks if `value` is classified as a `WeakSet` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isWeakSet(new WeakSet);
+ * // => true
+ *
+ * _.isWeakSet(new Set);
+ * // => false
+ */
+ function isWeakSet(value) {
+ return isObjectLike(value) && objectToString.call(value) == weakSetTag;
+ }
+
+ /**
* Checks if `value` is less than `other`.
*
* @static
* @returns {Array} Returns the converted array.
* @example
*
- * (function() {
- * return _.toArray(arguments).slice(1);
- * }(1, 2, 3));
- * // => [2, 3]
+ * _.toArray({ 'a': 1, 'b': 2 });
+ * // => [1, 2]
+ *
+ * _.toArray('abc');
+ * // => ['a', 'b', 'c']
+ *
+ * _.toArray(1);
+ * // => []
+ *
+ * _.toArray(null);
+ * // => []
*/
function toArray(value) {
- var length = value ? getLength(value) : 0;
- if (!isLength(length)) {
- return values(value);
- }
- if (!length) {
+ if (!value) {
return [];
}
- return arrayCopy(value);
+ if (isArrayLike(value)) {
+ return isString(value) ? stringToArray(value) : copyArray(value);
+ }
+ if (iteratorSymbol && value[iteratorSymbol]) {
+ return iteratorToArray(value[iteratorSymbol]());
+ }
+ var tag = getTag(value),
+ func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
+
+ return func(value);
+ }
+
+ /**
+ * Converts `value` to an integer.
+ *
+ * **Note:** This function is loosely based on [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {number} Returns the converted integer.
+ * @example
+ *
+ * _.toInteger(3);
+ * // => 3
+ *
+ * _.toInteger(Number.MIN_VALUE);
+ * // => 0
+ *
+ * _.toInteger(Infinity);
+ * // => 1.7976931348623157e+308
+ *
+ * _.toInteger('3');
+ * // => 3
+ */
+ function toInteger(value) {
+ if (!value) {
+ return value === 0 ? value : 0;
+ }
+ value = toNumber(value);
+ if (value === INFINITY || value === -INFINITY) {
+ var sign = (value < 0 ? -1 : 1);
+ return sign * MAX_INTEGER;
+ }
+ var remainder = value % 1;
+ return value === value ? (remainder ? value - remainder : value) : 0;
+ }
+
+ /**
+ * Converts `value` to an integer suitable for use as the length of an
+ * array-like object.
+ *
+ * **Note:** This method is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {number} Returns the converted integer.
+ * @example
+ *
+ * _.toLength(3);
+ * // => 3
+ *
+ * _.toLength(Number.MIN_VALUE);
+ * // => 0
+ *
+ * _.toLength(Infinity);
+ * // => 4294967295
+ *
+ * _.toLength('3');
+ * // => 3
+ */
+ function toLength(value) {
+ return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
+ }
+
+ /**
+ * Converts `value` to a number.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to process.
+ * @returns {number} Returns the number.
+ * @example
+ *
+ * _.toNumber(3);
+ * // => 3
+ *
+ * _.toNumber(Number.MIN_VALUE);
+ * // => 5e-324
+ *
+ * _.toNumber(Infinity);
+ * // => Infinity
+ *
+ * _.toNumber('3');
+ * // => 3
+ */
+ function toNumber(value) {
+ if (isObject(value)) {
+ var other = isFunction(value.valueOf) ? value.valueOf() : value;
+ value = isObject(other) ? (other + '') : other;
+ }
+ if (typeof value != 'string') {
+ return value === 0 ? value : +value;
+ }
+ value = value.replace(reTrim, '');
+ var isBinary = reIsBinary.test(value);
+ return (isBinary || reIsOctal.test(value))
+ ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
+ : (reIsBadHex.test(value) ? NAN : +value);
}
/**
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
- return baseCopy(value, keysIn(value));
+ return copyObject(value, keysIn(value));
+ }
+
+ /**
+ * Converts `value` to a safe integer. A safe integer can be compared and
+ * represented correctly.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {number} Returns the converted integer.
+ * @example
+ *
+ * _.toSafeInteger(3);
+ * // => 3
+ *
+ * _.toSafeInteger(Number.MIN_VALUE);
+ * // => 0
+ *
+ * _.toSafeInteger(Infinity);
+ * // => 9007199254740991
+ *
+ * _.toSafeInteger('3');
+ * // => 3
+ */
+ function toSafeInteger(value) {
+ return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
+ }
+
+ /**
+ * Converts `value` to a string if it's not one. An empty string is returned
+ * for `null` and `undefined` values. The sign of `-0` is preserved.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to process.
+ * @returns {string} Returns the string.
+ * @example
+ *
+ * _.toString(null);
+ * // => ''
+ *
+ * _.toString(-0);
+ * // => '-0'
+ *
+ * _.toString([1, 2, 3]);
+ * // => '1,2,3'
+ */
+ function toString(value) {
+ // Exit early for strings to avoid a performance hit in some environments.
+ if (typeof value == 'string') {
+ return value;
+ }
+ if (value == null) {
+ return '';
+ }
+ if (isSymbol(value)) {
+ return Symbol ? symbolToString.call(value) : '';
+ }
+ var result = (value + '');
+ return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/*------------------------------------------------------------------------*/
/**
- * Recursively merges own enumerable properties of the source object(s), that
- * don't resolve to `undefined` into the destination object. Subsequent sources
- * overwrite property assignments of previous sources. If `customizer` is
- * provided it's invoked to produce the merged values of the destination and
- * source properties. If `customizer` returns `undefined` merging is handled
- * by the method instead. The `customizer` is bound to `thisArg` and invoked
- * with five arguments: (objectValue, sourceValue, key, object, source).
+ * Assigns own enumerable properties of source objects to the destination
+ * object. Source objects are applied from left to right. Subsequent sources
+ * overwrite property assignments of previous sources.
+ *
+ * **Note:** This method mutates `object` and is loosely based on
+ * [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
- * @param {Function} [customizer] The function to customize assigned values.
- * @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
- * var users = {
- * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
- * };
- *
- * var ages = {
- * 'data': [{ 'age': 36 }, { 'age': 40 }]
- * };
+ * function Foo() {
+ * this.c = 3;
+ * }
*
- * _.merge(users, ages);
- * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
+ * function Bar() {
+ * this.e = 5;
+ * }
*
- * // using a customizer callback
- * var object = {
- * 'fruits': ['apple'],
- * 'vegetables': ['beet']
- * };
+ * Foo.prototype.d = 4;
+ * Bar.prototype.f = 6;
*
- * var other = {
- * 'fruits': ['banana'],
- * 'vegetables': ['carrot']
- * };
- *
- * _.merge(object, other, function(a, b) {
- * if (_.isArray(a)) {
- * return a.concat(b);
- * }
- * });
- * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
+ * _.assign({ 'a': 1 }, new Foo, new Bar);
+ * // => { 'a': 1, 'c': 3, 'e': 5 }
*/
- var merge = createAssigner(baseMerge);
+ var assign = createAssigner(function(object, source) {
+ copyObject(source, keys(source), object);
+ });
/**
- * Assigns own enumerable properties of source object(s) to the destination
- * object. Subsequent sources overwrite property assignments of previous sources.
- * If `customizer` is provided it's invoked to produce the assigned values.
- * The `customizer` is bound to `thisArg` and invoked with five arguments:
- * (objectValue, sourceValue, key, object, source).
+ * This method is like `_.assign` except that it iterates over own and
+ * inherited source properties.
*
- * **Note:** This method mutates `object` and is based on
- * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
+ * **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function Foo() {
+ * this.b = 2;
+ * }
+ *
+ * function Bar() {
+ * this.d = 4;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ * Bar.prototype.e = 5;
+ *
+ * _.assignIn({ 'a': 1 }, new Foo, new Bar);
+ * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }
+ */
+ var assignIn = createAssigner(function(object, source) {
+ copyObject(source, keysIn(source), object);
+ });
+
+ /**
+ * This method is like `_.assignIn` except that it accepts `customizer` which
+ * is invoked to produce the assigned values. If `customizer` returns `undefined`
+ * assignment is handled by the method instead. The `customizer` is invoked
+ * with five arguments: (objValue, srcValue, key, object, source).
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @alias extendWith
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
- * @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
- * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
- * // => { 'user': 'fred', 'age': 40 }
+ * function customizer(objValue, srcValue) {
+ * return _.isUndefined(objValue) ? srcValue : objValue;
+ * }
*
- * // using a customizer callback
- * var defaults = _.partialRight(_.assign, function(value, other) {
- * return _.isUndefined(value) ? other : value;
- * });
+ * var defaults = _.partialRight(_.assignInWith, customizer);
*
- * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
- * // => { 'user': 'barney', 'age': 36 }
+ * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
+ * // => { 'a': 1, 'b': 2 }
+ */
+ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
+ copyObjectWith(source, keysIn(source), object, customizer);
+ });
+
+ /**
+ * This method is like `_.assign` except that it accepts `customizer` which
+ * is invoked to produce the assigned values. If `customizer` returns `undefined`
+ * assignment is handled by the method instead. The `customizer` is invoked
+ * with five arguments: (objValue, srcValue, key, object, source).
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} sources The source objects.
+ * @param {Function} [customizer] The function to customize assigned values.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function customizer(objValue, srcValue) {
+ * return _.isUndefined(objValue) ? srcValue : objValue;
+ * }
+ *
+ * var defaults = _.partialRight(_.assignWith, customizer);
+ *
+ * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
+ * // => { 'a': 1, 'b': 2 }
*/
- var assign = createAssigner(function(object, source, customizer) {
- return customizer
- ? assignWith(object, source, customizer)
- : baseAssign(object, source);
+ var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
+ copyObjectWith(source, keys(source), object, customizer);
});
/**
- * Creates an object that inherits from the given `prototype` object. If a
- * `properties` object is provided its own enumerable properties are assigned
- * to the created object.
+ * Creates an array of values corresponding to `paths` of `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {...(string|string[])} [paths] The property paths of elements to pick,
+ * specified individually or in arrays.
+ * @returns {Array} Returns the new array of picked elements.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
+ *
+ * _.at(object, ['a[0].b.c', 'a[1]']);
+ * // => [3, 4]
+ *
+ * _.at(['a', 'b', 'c'], 0, 2);
+ * // => ['a', 'c']
+ */
+ var at = rest(function(object, paths) {
+ return baseAt(object, baseFlatten(paths, 1));
+ });
+
+ /**
+ * Creates an object that inherits from the `prototype` object. If a `properties`
+ * object is given its own enumerable properties are assigned to the created object.
*
* @static
* @memberOf _
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new object.
* @example
*
* circle instanceof Shape;
* // => true
*/
- function create(prototype, properties, guard) {
+ function create(prototype, properties) {
var result = baseCreate(prototype);
- if (guard && isIterateeCall(prototype, properties, guard)) {
- properties = undefined;
- }
return properties ? baseAssign(result, properties) : result;
}
/**
- * Assigns own enumerable properties of source object(s) to the destination
- * object for all destination properties that resolve to `undefined`. Once a
- * property is set, additional values of the same property are ignored.
+ * Assigns own and inherited enumerable properties of source objects to the
+ * destination object for all destination properties that resolve to `undefined`.
+ * Source objects are applied from left to right. Once a property is set,
+ * additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
- var defaults = createDefaults(assign, assignDefaults);
+ var defaults = rest(function(args) {
+ args.push(undefined, assignInDefaults);
+ return apply(assignInWith, undefined, args);
+ });
/**
* This method is like `_.defaults` except that it recursively assigns
* // => { 'user': { 'name': 'barney', 'age': 36 } }
*
*/
- var defaultsDeep = createDefaults(merge, mergeDefaults);
+ var defaultsDeep = rest(function(args) {
+ args.push(undefined, mergeDefaults);
+ return apply(mergeWith, undefined, args);
+ });
/**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
- *
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to search.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element, else `undefined`.
* @example
*
* 'pebbles': { 'age': 1, 'active': true }
* };
*
- * _.findKey(users, function(chr) {
- * return chr.age < 40;
- * });
+ * _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
- * // using the `_.matches` callback shorthand
+ * // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
- * // using the `_.matchesProperty` callback shorthand
- * _.findKey(users, 'active', false);
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.findKey(users, ['active', false]);
* // => 'fred'
*
- * // using the `_.property` callback shorthand
+ * // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
*/
- var findKey = createFindKey(baseForOwn);
+ function findKey(object, predicate) {
+ return baseFind(object, getIteratee(predicate, 3), baseForOwn, true);
+ }
/**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
- * If a property name is provided for `predicate` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `predicate` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
- *
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to search.
- * @param {Function|Object|string} [predicate=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element, else `undefined`.
* @example
*
* 'pebbles': { 'age': 1, 'active': true }
* };
*
- * _.findLastKey(users, function(chr) {
- * return chr.age < 40;
- * });
- * // => returns `pebbles` assuming `_.findKey` returns `barney`
+ * _.findLastKey(users, function(o) { return o.age < 40; });
+ * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
*
- * // using the `_.matches` callback shorthand
+ * // The `_.matches` iteratee shorthand.
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
- * // using the `_.matchesProperty` callback shorthand
- * _.findLastKey(users, 'active', false);
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.findLastKey(users, ['active', false]);
* // => 'fred'
*
- * // using the `_.property` callback shorthand
+ * // The `_.property` iteratee shorthand.
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/
- var findLastKey = createFindKey(baseForOwnRight);
+ function findLastKey(object, predicate) {
+ return baseFind(object, getIteratee(predicate, 3), baseForOwnRight, true);
+ }
/**
* Iterates over own and inherited enumerable properties of an object invoking
- * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
- * with three arguments: (value, key, object). Iteratee functions may exit
- * iteration early by explicitly returning `false`.
+ * `iteratee` for each property. The iteratee is invoked with three arguments:
+ * (value, key, object). Iteratee functions may exit iteration early by explicitly
+ * returning `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
- * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
+ * // => logs 'a', 'b', then 'c' (iteration order is not guaranteed)
*/
- var forIn = createForIn(baseFor);
+ function forIn(object, iteratee) {
+ return object == null
+ ? object
+ : baseFor(object, baseCastFunction(iteratee), keysIn);
+ }
/**
* This method is like `_.forIn` except that it iterates over properties of
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
- * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
+ * // => logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'
*/
- var forInRight = createForIn(baseForRight);
+ function forInRight(object, iteratee) {
+ return object == null
+ ? object
+ : baseForRight(object, baseCastFunction(iteratee), keysIn);
+ }
/**
* Iterates over own enumerable properties of an object invoking `iteratee`
- * for each property. The `iteratee` is bound to `thisArg` and invoked with
- * three arguments: (value, key, object). Iteratee functions may exit iteration
- * early by explicitly returning `false`.
+ * for each property. The iteratee is invoked with three arguments:
+ * (value, key, object). Iteratee functions may exit iteration early by
+ * explicitly returning `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
- * // => logs 'a' and 'b' (iteration order is not guaranteed)
+ * // => logs 'a' then 'b' (iteration order is not guaranteed)
*/
- var forOwn = createForOwn(baseForOwn);
+ function forOwn(object, iteratee) {
+ return object && baseForOwn(object, baseCastFunction(iteratee));
+ }
/**
* This method is like `_.forOwn` except that it iterates over properties of
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
- * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
+ * // => logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'
*/
- var forOwnRight = createForOwn(baseForOwnRight);
+ function forOwnRight(object, iteratee) {
+ return object && baseForOwnRight(object, baseCastFunction(iteratee));
+ }
/**
- * Creates an array of function property names from all enumerable properties,
- * own and inherited, of `object`.
+ * Creates an array of function property names from own enumerable properties
+ * of `object`.
*
* @static
* @memberOf _
- * @alias methods
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the new array of property names.
* @example
*
- * _.functions(_);
- * // => ['after', 'ary', 'assign', ...]
+ * function Foo() {
+ * this.a = _.constant('a');
+ * this.b = _.constant('b');
+ * }
+ *
+ * Foo.prototype.c = _.constant('c');
+ *
+ * _.functions(new Foo);
+ * // => ['a', 'b']
*/
function functions(object) {
- return baseFunctions(object, keysIn(object));
+ return object == null ? [] : baseFunctions(object, keys(object));
+ }
+
+ /**
+ * Creates an array of function property names from own and inherited
+ * enumerable properties of `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to inspect.
+ * @returns {Array} Returns the new array of property names.
+ * @example
+ *
+ * function Foo() {
+ * this.a = _.constant('a');
+ * this.b = _.constant('b');
+ * }
+ *
+ * Foo.prototype.c = _.constant('c');
+ *
+ * _.functionsIn(new Foo);
+ * // => ['a', 'b', 'c']
+ */
+ function functionsIn(object) {
+ return object == null ? [] : baseFunctions(object, keysIn(object));
}
/**
- * Gets the property value at `path` of `object`. If the resolved value is
+ * Gets the value at `path` of `object`. If the resolved value is
* `undefined` the `defaultValue` is used in its place.
*
* @static
* // => 'default'
*/
function get(object, path, defaultValue) {
- var result = object == null ? undefined : baseGet(object, toPath(path), (path + ''));
+ var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
- * Checks if `path` is a direct property.
+ * Checks if `path` is a direct property of `object`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
- * @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': { 'c': 3 } } };
+ * var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, ['a', 'b', 'c']);
* // => true
+ *
+ * _.has(other, 'a');
+ * // => false
*/
function has(object, path) {
- if (object == null) {
- return false;
- }
- var result = hasOwnProperty.call(object, path);
- if (!result && !isKey(path)) {
- path = toPath(path);
- object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
- if (object == null) {
- return false;
- }
- path = last(path);
- result = hasOwnProperty.call(object, path);
- }
- return result || (isLength(object.length) && isIndex(path, object.length) &&
- (isArray(object) || isArguments(object)));
+ return hasPath(object, path, baseHas);
+ }
+
+ /**
+ * Checks if `path` is a direct or inherited property of `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
+ * @example
+ *
+ * var object = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });
+ *
+ * _.hasIn(object, 'a');
+ * // => true
+ *
+ * _.hasIn(object, 'a.b.c');
+ * // => true
+ *
+ * _.hasIn(object, ['a', 'b', 'c']);
+ * // => true
+ *
+ * _.hasIn(object, 'b');
+ * // => false
+ */
+ function hasIn(object, path) {
+ return hasPath(object, path, baseHasIn);
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite property
- * assignments of previous values unless `multiValue` is `true`.
+ * assignments of previous values.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to invert.
- * @param {boolean} [multiValue] Allow multiple values per key.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new inverted object.
* @example
*
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
+ */
+ var invert = createInverter(function(result, value, key) {
+ result[value] = key;
+ }, constant(identity));
+
+ /**
+ * This method is like `_.invert` except that the inverted object is generated
+ * from the results of running each element of `object` through `iteratee`.
+ * The corresponding inverted value of each inverted key is an array of keys
+ * responsible for generating the inverted value. The iteratee is invoked
+ * with one argument: (value).
*
- * // with `multiValue`
- * _.invert(object, true);
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to invert.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {Object} Returns the new inverted object.
+ * @example
+ *
+ * var object = { 'a': 1, 'b': 2, 'c': 1 };
+ *
+ * _.invertBy(object);
* // => { '1': ['a', 'c'], '2': ['b'] }
+ *
+ * _.invertBy(object, function(value) {
+ * return 'group' + value;
+ * });
+ * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
- function invert(object, multiValue, guard) {
- if (guard && isIterateeCall(object, multiValue, guard)) {
- multiValue = undefined;
+ var invertBy = createInverter(function(result, value, key) {
+ if (hasOwnProperty.call(result, value)) {
+ result[value].push(key);
+ } else {
+ result[value] = [key];
}
- var index = -1,
- props = keys(object),
- length = props.length,
- result = {};
+ }, getIteratee);
- while (++index < length) {
- var key = props[index],
- value = object[key];
-
- if (multiValue) {
- if (hasOwnProperty.call(result, value)) {
- result[value].push(key);
- } else {
- result[value] = [key];
- }
- }
- else {
- result[value] = key;
- }
- }
- return result;
- }
+ /**
+ * Invokes the method at `path` of `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the method to invoke.
+ * @param {...*} [args] The arguments to invoke the method with.
+ * @returns {*} Returns the result of the invoked method.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
+ *
+ * _.invoke(object, 'a[0].b.c.slice', 1, 3);
+ * // => [2, 3]
+ */
+ var invoke = rest(baseInvoke);
/**
* Creates an array of the own enumerable property names of `object`.
* _.keys('hi');
* // => ['0', '1']
*/
- var keys = !nativeKeys ? shimKeys : function(object) {
- var Ctor = object == null ? undefined : object.constructor;
- if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
- (typeof object != 'function' && isArrayLike(object))) {
- return shimKeys(object);
+ function keys(object) {
+ var isProto = isPrototype(object);
+ if (!(isProto || isArrayLike(object))) {
+ return baseKeys(object);
}
- return isObject(object) ? nativeKeys(object) : [];
- };
+ var indexes = indexKeys(object),
+ skipIndexes = !!indexes,
+ result = indexes || [],
+ length = result.length;
+
+ for (var key in object) {
+ if (baseHas(object, key) &&
+ !(skipIndexes && (key == 'length' || isIndex(key, length))) &&
+ !(isProto && key == 'constructor')) {
+ result.push(key);
+ }
+ }
+ return result;
+ }
/**
* Creates an array of the own and inherited enumerable property names of `object`.
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
- if (object == null) {
- return [];
- }
- if (!isObject(object)) {
- object = Object(object);
- }
- var length = object.length;
- length = (length && isLength(length) &&
- (isArray(object) || isArguments(object)) && length) || 0;
-
- var Ctor = object.constructor,
- index = -1,
- isProto = typeof Ctor == 'function' && Ctor.prototype === object,
- result = Array(length),
- skipIndexes = length > 0;
+ var index = -1,
+ isProto = isPrototype(object),
+ props = baseKeysIn(object),
+ propsLength = props.length,
+ indexes = indexKeys(object),
+ skipIndexes = !!indexes,
+ result = indexes || [],
+ length = result.length;
- while (++index < length) {
- result[index] = (index + '');
- }
- for (var key in object) {
- if (!(skipIndexes && isIndex(key, length)) &&
+ while (++index < propsLength) {
+ var key = props[index];
+ if (!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
- * property of `object` through `iteratee`.
+ * property of `object` through `iteratee`. The iteratee is invoked with
+ * three arguments: (value, key, object).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @example
*
* });
* // => { 'a1': 1, 'b2': 2 }
*/
- var mapKeys = createObjectMapper(true);
+ function mapKeys(object, iteratee) {
+ var result = {};
+ iteratee = getIteratee(iteratee, 3);
+
+ baseForOwn(object, function(value, key, object) {
+ result[iteratee(value, key, object)] = value;
+ });
+ return result;
+ }
/**
* Creates an object with the same keys as `object` and values generated by
* running each own enumerable property of `object` through `iteratee`. The
- * iteratee function is bound to `thisArg` and invoked with three arguments:
- * (value, key, object).
- *
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * iteratee is invoked with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
- * @param {Function|Object|string} [iteratee=_.identity] The function invoked
- * per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @example
*
- * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
- * return n * 3;
- * });
- * // => { 'a': 3, 'b': 6 }
- *
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
- * // using the `_.property` callback shorthand
+ * _.mapValues(users, function(o) { return o.age; });
+ * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
+ *
+ * // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
- var mapValues = createObjectMapper();
+ function mapValues(object, iteratee) {
+ var result = {};
+ iteratee = getIteratee(iteratee, 3);
+
+ baseForOwn(object, function(value, key, object) {
+ result[key] = iteratee(value, key, object);
+ });
+ return result;
+ }
+
+ /**
+ * Recursively merges own and inherited enumerable properties of source objects
+ * into the destination object. Source properties that resolve to `undefined`
+ * are skipped if a destination value exists. Array and plain object properties
+ * are merged recursively. Other objects and value types are overridden by
+ * assignment. Source objects are applied from left to right. Subsequent
+ * sources overwrite property assignments of previous sources.
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * var users = {
+ * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
+ * };
+ *
+ * var ages = {
+ * 'data': [{ 'age': 36 }, { 'age': 40 }]
+ * };
+ *
+ * _.merge(users, ages);
+ * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
+ */
+ var merge = createAssigner(function(object, source, srcIndex) {
+ baseMerge(object, source, srcIndex);
+ });
+
+ /**
+ * This method is like `_.merge` except that it accepts `customizer` which
+ * is invoked to produce the merged values of the destination and source
+ * properties. If `customizer` returns `undefined` merging is handled by the
+ * method instead. The `customizer` is invoked with seven arguments:
+ * (objValue, srcValue, key, object, source, stack).
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} sources The source objects.
+ * @param {Function} customizer The function to customize assigned values.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function customizer(objValue, srcValue) {
+ * if (_.isArray(objValue)) {
+ * return objValue.concat(srcValue);
+ * }
+ * }
+ *
+ * var object = {
+ * 'fruits': ['apple'],
+ * 'vegetables': ['beet']
+ * };
+ *
+ * var other = {
+ * 'fruits': ['banana'],
+ * 'vegetables': ['carrot']
+ * };
+ *
+ * _.mergeWith(object, other, customizer);
+ * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
+ */
+ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
+ baseMerge(object, source, srcIndex, customizer);
+ });
/**
* The opposite of `_.pick`; this method creates an object composed of the
* @memberOf _
* @category Object
* @param {Object} object The source object.
- * @param {Function|...(string|string[])} [predicate] The function invoked per
- * iteration or property names to omit, specified as individual property
- * names or arrays of property names.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {...(string|string[])} [props] The property names to omit, specified
+ * individually or in arrays.
* @returns {Object} Returns the new object.
* @example
*
- * var object = { 'user': 'fred', 'age': 40 };
+ * var object = { 'a': 1, 'b': '2', 'c': 3 };
*
- * _.omit(object, 'age');
- * // => { 'user': 'fred' }
- *
- * _.omit(object, _.isNumber);
- * // => { 'user': 'fred' }
+ * _.omit(object, ['a', 'c']);
+ * // => { 'b': '2' }
*/
- var omit = restParam(function(object, props) {
+ var omit = rest(function(object, props) {
if (object == null) {
return {};
}
- if (typeof props[0] != 'function') {
- var props = arrayMap(baseFlatten(props), String);
- return pickByArray(object, baseDifference(keysIn(object), props));
- }
- var predicate = bindCallback(props[0], props[1], 3);
- return pickByCallback(object, function(value, key, object) {
- return !predicate(value, key, object);
- });
+ props = arrayMap(baseFlatten(props, 1), String);
+ return basePick(object, baseDifference(keysIn(object), props));
});
/**
- * Creates a two dimensional array of the key-value pairs for `object`,
- * e.g. `[[key1, value1], [key2, value2]]`.
+ * The opposite of `_.pickBy`; this method creates an object composed of
+ * the own and inherited enumerable properties of `object` that `predicate`
+ * doesn't return truthy for. The predicate is invoked with two arguments:
+ * (value, key).
*
* @static
* @memberOf _
* @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the new array of key-value pairs.
+ * @param {Object} object The source object.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per property.
+ * @returns {Object} Returns the new object.
* @example
*
- * _.pairs({ 'barney': 36, 'fred': 40 });
- * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
+ * var object = { 'a': 1, 'b': '2', 'c': 3 };
+ *
+ * _.omitBy(object, _.isNumber);
+ * // => { 'b': '2' }
*/
- function pairs(object) {
- object = toObject(object);
-
- var index = -1,
- props = keys(object),
- length = props.length,
- result = Array(length);
-
- while (++index < length) {
- var key = props[index];
- result[index] = [key, object[key]];
- }
- return result;
+ function omitBy(object, predicate) {
+ predicate = getIteratee(predicate);
+ return basePickBy(object, function(value, key) {
+ return !predicate(value, key);
+ });
}
/**
- * Creates an object composed of the picked `object` properties. Property
- * names may be specified as individual arguments or as arrays of property
- * names. If `predicate` is provided it's invoked for each property of `object`
- * picking the properties `predicate` returns truthy for. The predicate is
- * bound to `thisArg` and invoked with three arguments: (value, key, object).
+ * Creates an object composed of the picked `object` properties.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The source object.
- * @param {Function|...(string|string[])} [predicate] The function invoked per
- * iteration or property names to pick, specified as individual property
- * names or arrays of property names.
- * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @param {...(string|string[])} [props] The property names to pick, specified
+ * individually or in arrays.
* @returns {Object} Returns the new object.
* @example
*
- * var object = { 'user': 'fred', 'age': 40 };
+ * var object = { 'a': 1, 'b': '2', 'c': 3 };
*
- * _.pick(object, 'user');
- * // => { 'user': 'fred' }
- *
- * _.pick(object, _.isString);
- * // => { 'user': 'fred' }
+ * _.pick(object, ['a', 'c']);
+ * // => { 'a': 1, 'c': 3 }
*/
- var pick = restParam(function(object, props) {
- if (object == null) {
- return {};
- }
- return typeof props[0] == 'function'
- ? pickByCallback(object, bindCallback(props[0], props[1], 3))
- : pickByArray(object, baseFlatten(props));
+ var pick = rest(function(object, props) {
+ return object == null ? {} : basePick(object, baseFlatten(props, 1));
});
/**
+ * Creates an object composed of the `object` properties `predicate` returns
+ * truthy for. The predicate is invoked with two arguments: (value, key).
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The source object.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked per property.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * var object = { 'a': 1, 'b': '2', 'c': 3 };
+ *
+ * _.pickBy(object, _.isNumber);
+ * // => { 'a': 1, 'c': 3 }
+ */
+ function pickBy(object, predicate) {
+ return object == null ? {} : basePickBy(object, getIteratee(predicate));
+ }
+
+ /**
* This method is like `_.get` except that if the resolved value is a function
* it's invoked with the `this` binding of its parent object and its result
* is returned.
* _.result(object, 'a[0].b.c2');
* // => 4
*
- * _.result(object, 'a.b.c', 'default');
+ * _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
- * _.result(object, 'a.b.c', _.constant('default'));
+ * _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
*/
function result(object, path, defaultValue) {
- var result = object == null ? undefined : object[path];
+ if (!isKey(path, object)) {
+ path = baseCastPath(path);
+ var result = get(object, path);
+ object = parent(object, path);
+ } else {
+ result = object == null ? undefined : object[path];
+ }
if (result === undefined) {
- if (object != null && !isKey(path, object)) {
- path = toPath(path);
- object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
- result = object == null ? undefined : object[last(path)];
- }
- result = result === undefined ? defaultValue : result;
+ result = defaultValue;
}
return isFunction(result) ? result.call(object) : result;
}
/**
- * Sets the property value of `path` on `object`. If a portion of `path`
- * does not exist it's created.
+ * Sets the value at `path` of `object`. If a portion of `path` doesn't exist
+ * it's created. Arrays are created for missing index properties while objects
+ * are created for all other missing properties. Use `_.setWith` to customize
+ * `path` creation.
+ *
+ * **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @category Object
- * @param {Object} object The object to augment.
+ * @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* // => 5
*/
function set(object, path, value) {
- if (object == null) {
- return object;
- }
- var pathKey = (path + '');
- path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
+ return object == null ? object : baseSet(object, path, value);
+ }
- var index = -1,
- length = path.length,
- lastIndex = length - 1,
- nested = object;
+ /**
+ * This method is like `_.set` except that it accepts `customizer` which is
+ * invoked to produce the objects of `path`. If `customizer` returns `undefined`
+ * path creation is handled by the method instead. The `customizer` is invoked
+ * with three arguments: (nsValue, key, nsObject).
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to modify.
+ * @param {Array|string} path The path of the property to set.
+ * @param {*} value The value to set.
+ * @param {Function} [customizer] The function to customize assigned values.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * _.setWith({ '0': { 'length': 2 } }, '[0][1][2]', 3, Object);
+ * // => { '0': { '1': { '2': 3 }, 'length': 2 } }
+ */
+ function setWith(object, path, value, customizer) {
+ customizer = typeof customizer == 'function' ? customizer : undefined;
+ return object == null ? object : baseSet(object, path, value, customizer);
+ }
- while (nested != null && ++index < length) {
- var key = path[index];
- if (isObject(nested)) {
- if (index == lastIndex) {
- nested[key] = value;
- } else if (nested[key] == null) {
- nested[key] = isIndex(path[index + 1]) ? [] : {};
- }
- }
- nested = nested[key];
- }
- return object;
+ /**
+ * Creates an array of own enumerable key-value pairs for `object` which
+ * can be consumed by `_.fromPairs`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the new array of key-value pairs.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.toPairs(new Foo);
+ * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
+ */
+ function toPairs(object) {
+ return baseToPairs(object, keys(object));
+ }
+
+ /**
+ * Creates an array of own and inherited enumerable key-value pairs for
+ * `object` which can be consumed by `_.fromPairs`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the new array of key-value pairs.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.toPairsIn(new Foo);
+ * // => [['a', 1], ['b', 2], ['c', 1]] (iteration order is not guaranteed)
+ */
+ function toPairsIn(object) {
+ return baseToPairs(object, keysIn(object));
}
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own enumerable
* properties through `iteratee`, with each invocation potentially mutating
- * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
- * with four arguments: (accumulator, value, key, object). Iteratee functions
- * may exit iteration early by explicitly returning `false`.
+ * the `accumulator` object. The iteratee is invoked with four arguments:
+ * (accumulator, value, key, object). Iteratee functions may exit iteration
+ * early by explicitly returning `false`.
*
* @static
* @memberOf _
* @param {Array|Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
- * });
+ * }, []);
* // => [4, 9]
*
- * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
- * result[key] = n * 3;
- * });
- * // => { 'a': 3, 'b': 6 }
+ * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
+ * (result[value] || (result[value] = [])).push(key);
+ * }, {});
+ * // => { '1': ['a', 'c'], '2': ['b'] }
*/
- function transform(object, iteratee, accumulator, thisArg) {
+ function transform(object, iteratee, accumulator) {
var isArr = isArray(object) || isTypedArray(object);
- iteratee = getCallback(iteratee, thisArg, 4);
+ iteratee = getIteratee(iteratee, 4);
if (accumulator == null) {
if (isArr || isObject(object)) {
if (isArr) {
accumulator = isArray(object) ? new Ctor : [];
} else {
- accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
+ accumulator = isFunction(Ctor) ? baseCreate(getPrototypeOf(object)) : {};
}
} else {
accumulator = {};
}
/**
+ * Removes the property at `path` of `object`.
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to modify.
+ * @param {Array|string} path The path of the property to unset.
+ * @returns {boolean} Returns `true` if the property is deleted, else `false`.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': 7 } }] };
+ * _.unset(object, 'a[0].b.c');
+ * // => true
+ *
+ * console.log(object);
+ * // => { 'a': [{ 'b': {} }] };
+ *
+ * _.unset(object, 'a[0].b.c');
+ * // => true
+ *
+ * console.log(object);
+ * // => { 'a': [{ 'b': {} }] };
+ */
+ function unset(object, path) {
+ return object == null ? true : baseUnset(object, path);
+ }
+
+ /**
* Creates an array of the own enumerable property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
* // => ['h', 'i']
*/
function values(object) {
- return baseValues(object, keys(object));
+ return object ? baseValues(object, keys(object)) : [];
}
/**
- * Creates an array of the own and inherited enumerable property values
- * of `object`.
+ * Creates an array of the own and inherited enumerable property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* // => [1, 2, 3] (iteration order is not guaranteed)
*/
function valuesIn(object) {
- return baseValues(object, keysIn(object));
+ return object == null ? [] : baseValues(object, keysIn(object));
}
/*------------------------------------------------------------------------*/
/**
+ * Clamps `number` within the inclusive `lower` and `upper` bounds.
+ *
+ * @static
+ * @memberOf _
+ * @category Number
+ * @param {number} number The number to clamp.
+ * @param {number} [lower] The lower bound.
+ * @param {number} upper The upper bound.
+ * @returns {number} Returns the clamped number.
+ * @example
+ *
+ * _.clamp(-10, -5, 5);
+ * // => -5
+ *
+ * _.clamp(10, -5, 5);
+ * // => 5
+ */
+ function clamp(number, lower, upper) {
+ if (upper === undefined) {
+ upper = lower;
+ lower = undefined;
+ }
+ if (upper !== undefined) {
+ upper = toNumber(upper);
+ upper = upper === upper ? upper : 0;
+ }
+ if (lower !== undefined) {
+ lower = toNumber(lower);
+ lower = lower === lower ? lower : 0;
+ }
+ return baseClamp(toNumber(number), lower, upper);
+ }
+
+ /**
* Checks if `n` is between `start` and up to but not including, `end`. If
* `end` is not specified it's set to `start` with `start` then set to `0`.
+ * If `start` is greater than `end` the params are swapped to support
+ * negative ranges.
*
* @static
* @memberOf _
* @category Number
- * @param {number} n The number to check.
+ * @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
- * @returns {boolean} Returns `true` if `n` is in the range, else `false`.
+ * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @example
*
* _.inRange(3, 2, 4);
*
* _.inRange(5.2, 4);
* // => false
+ *
+ * _.inRange(-3, -2, -6);
+ * // => true
*/
- function inRange(value, start, end) {
- start = +start || 0;
+ function inRange(number, start, end) {
+ start = toNumber(start) || 0;
if (end === undefined) {
end = start;
start = 0;
} else {
- end = +end || 0;
+ end = toNumber(end) || 0;
}
- return value >= nativeMin(start, end) && value < nativeMax(start, end);
+ number = toNumber(number);
+ return baseInRange(number, start, end);
}
/**
- * Produces a random number between `min` and `max` (inclusive). If only one
- * argument is provided a number between `0` and the given number is returned.
- * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
- * number is returned instead of an integer.
+ * Produces a random number between the inclusive `lower` and `upper` bounds.
+ * If only one argument is provided a number between `0` and the given number
+ * is returned. If `floating` is `true`, or either `lower` or `upper` are floats,
+ * a floating-point number is returned instead of an integer.
+ *
+ * **Note:** JavaScript follows the IEEE-754 standard for resolving
+ * floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
* @category Number
- * @param {number} [min=0] The minimum possible value.
- * @param {number} [max=1] The maximum possible value.
+ * @param {number} [lower=0] The lower bound.
+ * @param {number} [upper=1] The upper bound.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
- function random(min, max, floating) {
- if (floating && isIterateeCall(min, max, floating)) {
- max = floating = undefined;
+ function random(lower, upper, floating) {
+ if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
+ upper = floating = undefined;
}
- var noMin = min == null,
- noMax = max == null;
-
- if (floating == null) {
- if (noMax && typeof min == 'boolean') {
- floating = min;
- min = 1;
+ if (floating === undefined) {
+ if (typeof upper == 'boolean') {
+ floating = upper;
+ upper = undefined;
}
- else if (typeof max == 'boolean') {
- floating = max;
- noMax = true;
+ else if (typeof lower == 'boolean') {
+ floating = lower;
+ lower = undefined;
}
}
- if (noMin && noMax) {
- max = 1;
- noMax = false;
+ if (lower === undefined && upper === undefined) {
+ lower = 0;
+ upper = 1;
}
- min = +min || 0;
- if (noMax) {
- max = min;
- min = 0;
- } else {
- max = +max || 0;
+ else {
+ lower = toNumber(lower) || 0;
+ if (upper === undefined) {
+ upper = lower;
+ lower = 0;
+ } else {
+ upper = toNumber(upper) || 0;
+ }
}
- if (floating || min % 1 || max % 1) {
+ if (lower > upper) {
+ var temp = lower;
+ lower = upper;
+ upper = temp;
+ }
+ if (floating || lower % 1 || upper % 1) {
var rand = nativeRandom();
- return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
+ return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
}
- return baseRandom(min, max);
+ return baseRandom(lower, upper);
}
/*------------------------------------------------------------------------*/
*/
var camelCase = createCompounder(function(result, word, index) {
word = word.toLowerCase();
- return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
+ return result + (index ? capitalize(word) : word);
});
/**
- * Capitalizes the first character of `string`.
+ * Converts the first character of `string` to upper case and the remaining
+ * to lower case.
*
* @static
* @memberOf _
* @returns {string} Returns the capitalized string.
* @example
*
- * _.capitalize('fred');
+ * _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize(string) {
- string = baseToString(string);
- return string && (string.charAt(0).toUpperCase() + string.slice(1));
+ return upperFirst(toString(string).toLowerCase());
}
/**
* // => 'deja vu'
*/
function deburr(string) {
- string = baseToString(string);
+ string = toString(string);
return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
}
* // => true
*/
function endsWith(string, target, position) {
- string = baseToString(string);
- target = (target + '');
+ string = toString(string);
+ target = typeof target == 'string' ? target : (target + '');
var length = string.length;
position = position === undefined
? length
- : nativeMin(position < 0 ? 0 : (+position || 0), length);
+ : baseClamp(toInteger(position), 0, length);
position -= target.length;
return position >= 0 && string.indexOf(target, position) == position;
}
/**
- * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
+ * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to
* their corresponding HTML entities.
*
- * **Note:** No other characters are escaped. To escape additional characters
- * use a third-party library like [_he_](https://mths.be/he).
+ * **Note:** No other characters are escaped. To escape additional
+ * characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
- * Backticks are escaped because in Internet Explorer < 9, they can break out
- * of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
+ * Backticks are escaped because in IE < 9, they can break out of
+ * attribute values or HTML comments. See [#59](https://html5sec.org/#59),
* [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
* [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
* for more details.
* // => 'fred, barney, & pebbles'
*/
function escape(string) {
- // Reset `lastIndex` because in IE < 9 `String#replace` does not.
- string = baseToString(string);
+ string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
/**
- * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
- * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
+ * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
+ * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
- * // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
+ * // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
- string = baseToString(string);
- return (string && reHasRegExpChars.test(string))
- ? string.replace(reRegExpChars, escapeRegExpChar)
- : (string || '(?:)');
+ string = toString(string);
+ return (string && reHasRegExpChar.test(string))
+ ? string.replace(reRegExpChar, '\\$&')
+ : string;
}
/**
});
/**
+ * Converts `string`, as space separated words, to lower case.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the lower cased string.
+ * @example
+ *
+ * _.lowerCase('--Foo-Bar');
+ * // => 'foo bar'
+ *
+ * _.lowerCase('fooBar');
+ * // => 'foo bar'
+ *
+ * _.lowerCase('__FOO_BAR__');
+ * // => 'foo bar'
+ */
+ var lowerCase = createCompounder(function(result, word, index) {
+ return result + (index ? ' ' : '') + word.toLowerCase();
+ });
+
+ /**
+ * Converts the first character of `string` to lower case.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the converted string.
+ * @example
+ *
+ * _.lowerFirst('Fred');
+ * // => 'fred'
+ *
+ * _.lowerFirst('FRED');
+ * // => 'fRED'
+ */
+ var lowerFirst = createCaseFirst('toLowerCase');
+
+ /**
+ * Converts the first character of `string` to upper case.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the converted string.
+ * @example
+ *
+ * _.upperFirst('fred');
+ * // => 'Fred'
+ *
+ * _.upperFirst('FRED');
+ * // => 'FRED'
+ */
+ var upperFirst = createCaseFirst('toUpperCase');
+
+ /**
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* // => 'abc'
*/
function pad(string, length, chars) {
- string = baseToString(string);
- length = +length;
+ string = toString(string);
+ length = toInteger(length);
- var strLength = string.length;
- if (strLength >= length || !nativeIsFinite(length)) {
+ var strLength = stringSize(string);
+ if (!length || strLength >= length) {
return string;
}
var mid = (length - strLength) / 2,
leftLength = nativeFloor(mid),
rightLength = nativeCeil(mid);
- chars = createPadding('', rightLength, chars);
- return chars.slice(0, leftLength) + string + chars;
+ return createPadding('', leftLength, chars) + string + createPadding('', rightLength, chars);
}
/**
- * Pads `string` on the left side if it's shorter than `length`. Padding
+ * Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @returns {string} Returns the padded string.
* @example
*
- * _.padLeft('abc', 6);
- * // => ' abc'
+ * _.padEnd('abc', 6);
+ * // => 'abc '
*
- * _.padLeft('abc', 6, '_-');
- * // => '_-_abc'
+ * _.padEnd('abc', 6, '_-');
+ * // => 'abc_-_'
*
- * _.padLeft('abc', 3);
+ * _.padEnd('abc', 3);
* // => 'abc'
*/
- var padLeft = createPadDir();
+ function padEnd(string, length, chars) {
+ string = toString(string);
+ return string + createPadding(string, length, chars);
+ }
/**
- * Pads `string` on the right side if it's shorter than `length`. Padding
+ * Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @returns {string} Returns the padded string.
* @example
*
- * _.padRight('abc', 6);
- * // => 'abc '
+ * _.padStart('abc', 6);
+ * // => ' abc'
*
- * _.padRight('abc', 6, '_-');
- * // => 'abc_-_'
+ * _.padStart('abc', 6, '_-');
+ * // => '_-_abc'
*
- * _.padRight('abc', 3);
+ * _.padStart('abc', 3);
* // => 'abc'
*/
- var padRight = createPadDir(true);
+ function padStart(string, length, chars) {
+ string = toString(string);
+ return createPadding(string, length, chars) + string;
+ }
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
* in which case a `radix` of `16` is used.
*
- * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
+ * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#x15.1.2.2)
* of `parseInt`.
*
* @static
* @memberOf _
* @category String
* @param {string} string The string to convert.
- * @param {number} [radix] The radix to interpret `value` by.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param {number} [radix=10] The radix to interpret `value` by.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
- // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
// Chrome fails to trim leading <BOM> whitespace characters.
// See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
- if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
+ if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
- string = trim(string);
+ string = toString(string).replace(reTrim, '');
return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
}
* // => ''
*/
function repeat(string, n) {
+ string = toString(string);
+ n = toInteger(n);
+
var result = '';
- string = baseToString(string);
- n = +n;
- if (n < 1 || !string || !nativeIsFinite(n)) {
+ if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
}
/**
+ * Replaces matches for `pattern` in `string` with `replacement`.
+ *
+ * **Note:** This method is based on [`String#replace`](https://mdn.io/String/replace).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to modify.
+ * @param {RegExp|string} pattern The pattern to replace.
+ * @param {Function|string} replacement The match replacement.
+ * @returns {string} Returns the modified string.
+ * @example
+ *
+ * _.replace('Hi Fred', 'Fred', 'Barney');
+ * // => 'Hi Barney'
+ */
+ function replace() {
+ var args = arguments,
+ string = toString(args[0]);
+
+ return args.length < 3 ? string : string.replace(args[1], args[2]);
+ }
+
+ /**
* Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
*
* @static
});
/**
+ * Splits `string` by `separator`.
+ *
+ * **Note:** This method is based on [`String#split`](https://mdn.io/String/split).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to split.
+ * @param {RegExp|string} separator The separator pattern to split by.
+ * @param {number} [limit] The length to truncate results to.
+ * @returns {Array} Returns the new array of string segments.
+ * @example
+ *
+ * _.split('a-b-c', '-', 2);
+ * // => ['a', 'b']
+ */
+ function split(string, separator, limit) {
+ return toString(string).split(separator, limit);
+ }
+
+ /**
* Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* // => 'Foo Bar'
*/
var startCase = createCompounder(function(result, word, index) {
- return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
+ return result + (index ? ' ' : '') + capitalize(word);
});
/**
* // => true
*/
function startsWith(string, target, position) {
- string = baseToString(string);
- position = position == null
- ? 0
- : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
-
+ string = toString(string);
+ position = baseClamp(toInteger(position), 0, string.length);
return string.lastIndexOf(target, position) == position;
}
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
- * object is provided it takes precedence over `_.templateSettings` values.
+ * object is given it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* @param {RegExp} [options.interpolate] The "interpolate" delimiter.
* @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
* @param {string} [options.variable] The data object variable name.
- * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
- * // using the "interpolate" delimiter to create a compiled template
+ * // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
- * // using the HTML "escape" delimiter to escape data property values
+ * // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b><script></b>'
*
- * // using the "evaluate" delimiter to execute JavaScript and generate HTML
+ * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
- * // using the internal `print` function in "evaluate" delimiters
+ * // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
- * // using the ES delimiter as an alternative to the default "interpolate" delimiter
+ * // Use the ES delimiter as an alternative to the default "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
- * // using custom template delimiters
+ * // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
- * // using backslashes to treat delimiters as plain text
+ * // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
- * // using the `imports` option to import `jQuery` as `jq`
+ * // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
- * // using the `sourceURL` option to specify a custom sourceURL for the template
+ * // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
*
- * // using the `variable` option to ensure a with-statement isn't used in the compiled template
+ * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // return __p;
* // }
*
- * // using the `source` property to inline compiled templates for meaningful
- * // line numbers in error messages and a stack trace
+ * // Use the `source` property to inline compiled templates for meaningful
+ * // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(cwd, 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
- function template(string, options, otherOptions) {
+ function template(string, options, guard) {
// Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
- if (otherOptions && isIterateeCall(string, options, otherOptions)) {
- options = otherOptions = undefined;
+ if (guard && isIterateeCall(string, options, guard)) {
+ options = undefined;
}
- string = baseToString(string);
- options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
+ string = toString(string);
+ options = assignInWith({}, options, settings, assignInDefaults);
- var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
+ var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
}
index = offset + match.length;
- // The JS engine embedded in Adobe products requires returning the `match`
- // string in order to produce the correct `offset` value.
+ // The JS engine embedded in Adobe products needs `match` returned in
+ // order to produce the correct `offset` value.
return match;
});
'return __p\n}';
var result = attempt(function() {
- return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
+ return Function(importsKeys, sourceURL + 'return ' + source)
+ .apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
}
/**
+ * Converts `string`, as a whole, to lower case.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the lower cased string.
+ * @example
+ *
+ * _.toLower('--Foo-Bar');
+ * // => '--foo-bar'
+ *
+ * _.toLower('fooBar');
+ * // => 'foobar'
+ *
+ * _.toLower('__FOO_BAR__');
+ * // => '__foo_bar__'
+ */
+ function toLower(value) {
+ return toString(value).toLowerCase();
+ }
+
+ /**
+ * Converts `string`, as a whole, to upper case.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the upper cased string.
+ * @example
+ *
+ * _.toUpper('--foo-bar');
+ * // => '--FOO-BAR'
+ *
+ * _.toUpper('fooBar');
+ * // => 'FOOBAR'
+ *
+ * _.toUpper('__foo_bar__');
+ * // => '__FOO_BAR__'
+ */
+ function toUpper(value) {
+ return toString(value).toUpperCase();
+ }
+
+ /**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
- var value = string;
- string = baseToString(string);
+ string = toString(string);
if (!string) {
return string;
}
- if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
- return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
+ if (guard || chars === undefined) {
+ return string.replace(reTrim, '');
}
chars = (chars + '');
- return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
+ if (!chars) {
+ return string;
+ }
+ var strSymbols = stringToArray(string),
+ chrSymbols = stringToArray(chars);
+
+ return strSymbols
+ .slice(charsStartIndex(strSymbols, chrSymbols), charsEndIndex(strSymbols, chrSymbols) + 1)
+ .join('');
}
/**
- * Removes leading whitespace or specified characters from `string`.
+ * Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
- * _.trimLeft(' abc ');
- * // => 'abc '
+ * _.trimEnd(' abc ');
+ * // => ' abc'
*
- * _.trimLeft('-_-abc-_-', '_-');
- * // => 'abc-_-'
+ * _.trimEnd('-_-abc-_-', '_-');
+ * // => '-_-abc'
*/
- function trimLeft(string, chars, guard) {
- var value = string;
- string = baseToString(string);
+ function trimEnd(string, chars, guard) {
+ string = toString(string);
if (!string) {
return string;
}
- if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
- return string.slice(trimmedLeftIndex(string));
+ if (guard || chars === undefined) {
+ return string.replace(reTrimEnd, '');
}
- return string.slice(charsLeftIndex(string, (chars + '')));
+ chars = (chars + '');
+ if (!chars) {
+ return string;
+ }
+ var strSymbols = stringToArray(string);
+ return strSymbols
+ .slice(0, charsEndIndex(strSymbols, stringToArray(chars)) + 1)
+ .join('');
}
/**
- * Removes trailing whitespace or specified characters from `string`.
+ * Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
- * _.trimRight(' abc ');
- * // => ' abc'
+ * _.trimStart(' abc ');
+ * // => 'abc '
*
- * _.trimRight('-_-abc-_-', '_-');
- * // => '-_-abc'
+ * _.trimStart('-_-abc-_-', '_-');
+ * // => 'abc-_-'
*/
- function trimRight(string, chars, guard) {
- var value = string;
- string = baseToString(string);
+ function trimStart(string, chars, guard) {
+ string = toString(string);
if (!string) {
return string;
}
- if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
- return string.slice(0, trimmedRightIndex(string) + 1);
+ if (guard || chars === undefined) {
+ return string.replace(reTrimStart, '');
}
- return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
+ chars = (chars + '');
+ if (!chars) {
+ return string;
+ }
+ var strSymbols = stringToArray(string);
+ return strSymbols
+ .slice(charsStartIndex(strSymbols, stringToArray(chars)))
+ .join('');
}
/**
* @memberOf _
* @category String
* @param {string} [string=''] The string to truncate.
- * @param {Object|number} [options] The options object or maximum string length.
+ * @param {Object} [options=({})] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the truncated string.
* @example
*
- * _.trunc('hi-diddly-ho there, neighborino');
+ * _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
- * _.trunc('hi-diddly-ho there, neighborino', 24);
- * // => 'hi-diddly-ho there, n...'
- *
- * _.trunc('hi-diddly-ho there, neighborino', {
+ * _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
- * _.trunc('hi-diddly-ho there, neighborino', {
+ * _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
- * _.trunc('hi-diddly-ho there, neighborino', {
+ * _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/
- function trunc(string, options, guard) {
- if (guard && isIterateeCall(string, options, guard)) {
- options = undefined;
- }
+ function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
- if (options != null) {
- if (isObject(options)) {
- var separator = 'separator' in options ? options.separator : separator;
- length = 'length' in options ? (+options.length || 0) : length;
- omission = 'omission' in options ? baseToString(options.omission) : omission;
- } else {
- length = +options || 0;
- }
+ if (isObject(options)) {
+ var separator = 'separator' in options ? options.separator : separator;
+ length = 'length' in options ? toInteger(options.length) : length;
+ omission = 'omission' in options ? toString(options.omission) : omission;
}
- string = baseToString(string);
- if (length >= string.length) {
+ string = toString(string);
+
+ var strLength = string.length;
+ if (reHasComplexSymbol.test(string)) {
+ var strSymbols = stringToArray(string);
+ strLength = strSymbols.length;
+ }
+ if (length >= strLength) {
return string;
}
- var end = length - omission.length;
+ var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
- var result = string.slice(0, end);
- if (separator == null) {
+ var result = strSymbols
+ ? strSymbols.slice(0, end).join('')
+ : string.slice(0, end);
+
+ if (separator === undefined) {
return result + omission;
}
+ if (strSymbols) {
+ end += (result.length - end);
+ }
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
- newEnd,
- substring = string.slice(0, end);
+ substring = result;
if (!separator.global) {
- separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
+ separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
- newEnd = match.index;
+ var newEnd = match.index;
}
- result = result.slice(0, newEnd == null ? end : newEnd);
+ result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(separator, end) != end) {
var index = result.lastIndexOf(separator);
* // => 'fred, barney, & pebbles'
*/
function unescape(string) {
- string = baseToString(string);
+ string = toString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}
/**
+ * Converts `string`, as space separated words, to upper case.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the upper cased string.
+ * @example
+ *
+ * _.upperCase('--foo-bar');
+ * // => 'FOO BAR'
+ *
+ * _.upperCase('fooBar');
+ * // => 'FOO BAR'
+ *
+ * _.upperCase('__foo_bar__');
+ * // => 'FOO BAR'
+ */
+ var upperCase = createCompounder(function(result, word, index) {
+ return result + (index ? ' ' : '') + word.toUpperCase();
+ });
+
+ /**
* Splits `string` into an array of its words.
*
* @static
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
- if (guard && isIterateeCall(string, pattern, guard)) {
- pattern = undefined;
+ string = toString(string);
+ pattern = guard ? undefined : pattern;
+
+ if (pattern === undefined) {
+ pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord;
}
- string = baseToString(string);
- return string.match(pattern || reWords) || [];
+ return string.match(pattern) || [];
}
/*------------------------------------------------------------------------*/
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {Function} func The function to attempt.
* @returns {*} Returns the `func` result or error object.
* @example
*
- * // avoid throwing errors for invalid selectors
+ * // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
* elements = [];
* }
*/
- var attempt = restParam(function(func, args) {
+ var attempt = rest(function(func, args) {
try {
- return func.apply(undefined, args);
- } catch(e) {
+ return apply(func, undefined, args);
+ } catch (e) {
return isError(e) ? e : new Error(e);
}
});
/**
- * Creates a function that invokes `func` with the `this` binding of `thisArg`
- * and arguments of the created function. If `func` is a property name the
- * created callback returns the property value for a given element. If `func`
- * is an object the created callback returns `true` for elements that contain
- * the equivalent object properties, otherwise it returns `false`.
+ * Binds methods of an object to the object itself, overwriting the existing
+ * method.
+ *
+ * **Note:** This method doesn't set the "length" property of bound functions.
*
* @static
* @memberOf _
- * @alias iteratee
- * @category Utility
- * @param {*} [func=_.identity] The value to convert to a callback.
- * @param {*} [thisArg] The `this` binding of `func`.
- * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
- * @returns {Function} Returns the callback.
+ * @category Util
+ * @param {Object} object The object to bind and assign the bound methods to.
+ * @param {...(string|string[])} methodNames The object method names to bind,
+ * specified individually or in arrays.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * var view = {
+ * 'label': 'docs',
+ * 'onClick': function() {
+ * console.log('clicked ' + this.label);
+ * }
+ * };
+ *
+ * _.bindAll(view, 'onClick');
+ * jQuery(element).on('click', view.onClick);
+ * // => logs 'clicked docs' when clicked
+ */
+ var bindAll = rest(function(object, methodNames) {
+ arrayEach(baseFlatten(methodNames, 1), function(key) {
+ object[key] = bind(object[key], object);
+ });
+ return object;
+ });
+
+ /**
+ * Creates a function that iterates over `pairs` invoking the corresponding
+ * function of the first predicate to return truthy. The predicate-function
+ * pairs are invoked with the `this` binding and arguments of the created
+ * function.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {Array} pairs The predicate-function pairs.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var func = _.cond([
+ * [_.matches({ 'a': 1 }), _.constant('matches A')],
+ * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
+ * [_.constant(true), _.constant('no match')]
+ * ]);
+ *
+ * func({ 'a': 1, 'b': 2 });
+ * // => 'matches A'
+ *
+ * func({ 'a': 0, 'b': 1 });
+ * // => 'matches B'
+ *
+ * func({ 'a': '1', 'b': '2' });
+ * // => 'no match'
+ */
+ function cond(pairs) {
+ var length = pairs ? pairs.length : 0,
+ toIteratee = getIteratee();
+
+ pairs = !length ? [] : arrayMap(pairs, function(pair) {
+ if (typeof pair[1] != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ return [toIteratee(pair[0]), pair[1]];
+ });
+
+ return rest(function(args) {
+ var index = -1;
+ while (++index < length) {
+ var pair = pairs[index];
+ if (apply(pair[0], this, args)) {
+ return apply(pair[1], this, args);
+ }
+ }
+ });
+ }
+
+ /**
+ * Creates a function that invokes the predicate properties of `source` with
+ * the corresponding property values of a given object, returning `true` if
+ * all predicates return truthy, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {Object} source The object of property predicates to conform to.
+ * @returns {Function} Returns the new function.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 40 }
* ];
*
- * // wrap to create custom callback shorthands
- * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
- * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
- * if (!match) {
- * return callback(func, thisArg);
- * }
- * return function(object) {
- * return match[2] == 'gt'
- * ? object[match[1]] > match[3]
- * : object[match[1]] < match[3];
- * };
- * });
- *
- * _.filter(users, 'age__gt36');
+ * _.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) }));
* // => [{ 'user': 'fred', 'age': 40 }]
*/
- function callback(func, thisArg, guard) {
- if (guard && isIterateeCall(func, thisArg, guard)) {
- thisArg = undefined;
- }
- return isObjectLike(func)
- ? matches(func)
- : baseCallback(func, thisArg);
+ function conforms(source) {
+ return baseConforms(baseClone(source, true));
}
/**
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new function.
* @example
}
/**
- * This method returns the first argument provided to it.
+ * Creates a function that returns the result of invoking the given functions
+ * with the `this` binding of the created function, where each successive
+ * invocation is supplied the return value of the previous.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {...(Function|Function[])} [funcs] Functions to invoke.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * function square(n) {
+ * return n * n;
+ * }
+ *
+ * var addSquare = _.flow(_.add, square);
+ * addSquare(1, 2);
+ * // => 9
+ */
+ var flow = createFlow();
+
+ /**
+ * This method is like `_.flow` except that it creates a function that
+ * invokes the given functions from right to left.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
+ * @param {...(Function|Function[])} [funcs] Functions to invoke.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * function square(n) {
+ * return n * n;
+ * }
+ *
+ * var addSquare = _.flowRight(square, _.add);
+ * addSquare(1, 2);
+ * // => 9
+ */
+ var flowRight = createFlow(true);
+
+ /**
+ * This method returns the first argument given to it.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
}
/**
- * Creates a function that performs a deep comparison between a given object
- * and `source`, returning `true` if the given object has equivalent property
- * values, else `false`.
+ * Creates a function that invokes `func` with the arguments of the created
+ * function. If `func` is a property name the created callback returns the
+ * property value for a given element. If `func` is an object the created
+ * callback returns `true` for elements that contain the equivalent object
+ * properties, otherwise it returns `false`.
*
- * **Note:** This method supports comparing arrays, booleans, `Date` objects,
- * numbers, `Object` objects, regexes, and strings. Objects are compared by
- * their own, not inherited, enumerable properties. For comparing a single
- * own or inherited property value see `_.matchesProperty`.
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {*} [func=_.identity] The value to convert to a callback.
+ * @returns {Function} Returns the callback.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 }
+ * ];
+ *
+ * // Create custom iteratee shorthands.
+ * _.iteratee = _.wrap(_.iteratee, function(callback, func) {
+ * var p = /^(\S+)\s*([<>])\s*(\S+)$/.exec(func);
+ * return !p ? callback(func) : function(object) {
+ * return (p[2] == '>' ? object[p[1]] > p[3] : object[p[1]] < p[3]);
+ * };
+ * });
+ *
+ * _.filter(users, 'age > 36');
+ * // => [{ 'user': 'fred', 'age': 40 }]
+ */
+ function iteratee(func) {
+ return baseIteratee(typeof func == 'function' ? func : baseClone(func, true));
+ }
+
+ /**
+ * Creates a function that performs a partial deep comparison between a given
+ * object and `source`, returning `true` if the given object has equivalent
+ * property values, else `false`. The created function is equivalent to
+ * `_.isMatch` with a `source` partially applied.
+ *
+ * **Note:** This method supports comparing the same values as `_.isEqual`.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
* @example
}
/**
- * Creates a function that compares the property value of `path` on a given
- * object to `value`.
+ * Creates a function that performs a partial deep comparison between the
+ * value at `path` of a given object to `srcValue`, returning `true` if the
+ * object value is equivalent, else `false`.
*
- * **Note:** This method supports comparing arrays, booleans, `Date` objects,
- * numbers, `Object` objects, regexes, and strings. Objects are compared by
- * their own, not inherited, enumerable properties.
+ * **Note:** This method supports comparing the same values as `_.isEqual`.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {Array|string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new function.
}
/**
- * Creates a function that invokes the method at `path` on a given object.
+ * Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new function.
* _.map(objects, _.method('a.b.c'));
* // => [2, 1]
*
- * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
+ * _.invokeMap(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
* // => [1, 2]
*/
- var method = restParam(function(path, args) {
+ var method = rest(function(path, args) {
return function(object) {
- return invokePath(object, path, args);
+ return baseInvoke(object, path, args);
};
});
/**
* The opposite of `_.method`; this method creates a function that invokes
- * the method at a given path on `object`. Any additional arguments are
+ * the method at a given path of `object`. Any additional arguments are
* provided to the invoked method.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {Object} object The object to query.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new function.
* _.map([['a', '2'], ['c', '0']], _.methodOf(object));
* // => [2, 0]
*/
- var methodOf = restParam(function(object, args) {
+ var methodOf = rest(function(object, args) {
return function(path) {
- return invokePath(object, path, args);
+ return baseInvoke(object, path, args);
};
});
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {Function|Object} [object=lodash] The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options] The options object.
* // => ['e']
*/
function mixin(object, source, options) {
- if (options == null) {
- var isObj = isObject(source),
- props = isObj ? keys(source) : undefined,
- methodNames = (props && props.length) ? baseFunctions(source, props) : undefined;
-
- if (!(methodNames ? methodNames.length : isObj)) {
- methodNames = false;
- options = source;
- source = object;
- object = this;
- }
- }
- if (!methodNames) {
+ var props = keys(source),
+ methodNames = baseFunctions(source, props);
+
+ if (options == null &&
+ !(isObject(source) && (methodNames.length || !props.length))) {
+ options = source;
+ source = object;
+ object = this;
methodNames = baseFunctions(source, keys(source));
}
- var chain = true,
- index = -1,
- isFunc = isFunction(object),
- length = methodNames.length;
-
- if (options === false) {
- chain = false;
- } else if (isObject(options) && 'chain' in options) {
- chain = options.chain;
- }
- while (++index < length) {
- var methodName = methodNames[index],
- func = source[methodName];
+ var chain = (isObject(options) && 'chain' in options) ? options.chain : true,
+ isFunc = isFunction(object);
+ arrayEach(methodNames, function(methodName) {
+ var func = source[methodName];
object[methodName] = func;
if (isFunc) {
- object.prototype[methodName] = (function(func) {
- return function() {
- var chainAll = this.__chain__;
- if (chain || chainAll) {
- var result = object(this.__wrapped__),
- actions = result.__actions__ = arrayCopy(this.__actions__);
-
- actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
- result.__chain__ = chainAll;
- return result;
- }
- return func.apply(object, arrayPush([this.value()], arguments));
- };
- }(func));
+ object.prototype[methodName] = function() {
+ var chainAll = this.__chain__;
+ if (chain || chainAll) {
+ var result = object(this.__wrapped__),
+ actions = result.__actions__ = copyArray(this.__actions__);
+
+ actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
+ result.__chain__ = chainAll;
+ return result;
+ }
+ return func.apply(object, arrayPush([this.value()], arguments));
+ };
}
- }
+ });
+
return object;
}
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
- root._ = oldDash;
+ if (root._ === this) {
+ root._ = oldDash;
+ }
return this;
}
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @example
*
* var object = { 'user': 'fred' };
}
/**
- * Creates a function that returns the property value at `path` on a
- * given object.
+ * Creates a function that returns its nth argument.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {number} [n=0] The index of the argument to return.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var func = _.nthArg(1);
+ *
+ * func('a', 'b', 'c');
+ * // => 'b'
+ */
+ function nthArg(n) {
+ n = toInteger(n);
+ return function() {
+ return arguments[n];
+ };
+ }
+
+ /**
+ * Creates a function that invokes `iteratees` with the arguments provided
+ * to the created function and returns their results.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {...(Function|Function[])} iteratees The iteratees to invoke.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var func = _.over(Math.max, Math.min);
+ *
+ * func(1, 2, 3, 4);
+ * // => [4, 1]
+ */
+ var over = createOver(arrayMap);
+
+ /**
+ * Creates a function that checks if **all** of the `predicates` return
+ * truthy when invoked with the arguments provided to the created function.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
+ * @param {...(Function|Function[])} predicates The predicates to check.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var func = _.overEvery(Boolean, isFinite);
+ *
+ * func('1');
+ * // => true
+ *
+ * func(null);
+ * // => false
+ *
+ * func(NaN);
+ * // => false
+ */
+ var overEvery = createOver(arrayEvery);
+
+ /**
+ * Creates a function that checks if **any** of the `predicates` return
+ * truthy when invoked with the arguments provided to the created function.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {...(Function|Function[])} predicates The predicates to check.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var func = _.overSome(Boolean, isFinite);
+ *
+ * func('1');
+ * // => true
+ *
+ * func(null);
+ * // => true
+ *
+ * func(NaN);
+ * // => false
+ */
+ var overSome = createOver(arraySome);
+
+ /**
+ * Creates a function that returns the value at `path` of a given object.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
* @example
* _.map(objects, _.property('a.b.c'));
* // => [2, 1]
*
- * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
+ * _.map(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
* // => [1, 2]
*/
function property(path) {
/**
* The opposite of `_.property`; this method creates a function that returns
- * the property value at a given path on `object`.
+ * the value at a given path of `object`.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {Object} object The object to query.
* @returns {Function} Returns the new function.
* @example
*/
function propertyOf(object) {
return function(path) {
- return baseGet(object, toPath(path), (path + ''));
+ return object == null ? undefined : baseGet(object, path);
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
- * `start` up to, but not including, `end`. If `end` is not specified it's
- * set to `start` with `start` then set to `0`. If `end` is less than `start`
- * a zero-length range is created unless a negative `step` is specified.
+ * `start` up to, but not including, `end`. A step of `-1` is used if a negative
+ * `start` is specified without an `end` or `step`. If `end` is not specified
+ * it's set to `start` with `start` then set to `0`.
+ *
+ * **Note:** JavaScript follows the IEEE-754 standard for resolving
+ * floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* _.range(4);
* // => [0, 1, 2, 3]
*
+ * _.range(-4);
+ * // => [0, -1, -2, -3]
+ *
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0);
* // => []
*/
- function range(start, end, step) {
- if (step && isIterateeCall(start, end, step)) {
- end = step = undefined;
- }
- start = +start || 0;
- step = step == null ? 1 : (+step || 0);
-
- if (end == null) {
- end = start;
- start = 0;
- } else {
- end = +end || 0;
- }
- // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
- // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
- var index = -1,
- length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
- result = Array(length);
+ var range = createRange();
- while (++index < length) {
- result[index] = start;
- start += step;
- }
- return result;
- }
+ /**
+ * This method is like `_.range` except that it populates values in
+ * descending order.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {number} [start=0] The start of the range.
+ * @param {number} end The end of the range.
+ * @param {number} [step=1] The value to increment or decrement by.
+ * @returns {Array} Returns the new array of numbers.
+ * @example
+ *
+ * _.rangeRight(4);
+ * // => [3, 2, 1, 0]
+ *
+ * _.rangeRight(-4);
+ * // => [-3, -2, -1, 0]
+ *
+ * _.rangeRight(1, 5);
+ * // => [4, 3, 2, 1]
+ *
+ * _.rangeRight(0, 20, 5);
+ * // => [15, 10, 5, 0]
+ *
+ * _.rangeRight(0, -4, -1);
+ * // => [-3, -2, -1, 0]
+ *
+ * _.rangeRight(1, 4, 0);
+ * // => [1, 1, 1]
+ *
+ * _.rangeRight(0);
+ * // => []
+ */
+ var rangeRight = createRange(true);
/**
- * Invokes the iteratee function `n` times, returning an array of the results
- * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
- * one argument; (index).
+ * Invokes the iteratee `n` times, returning an array of the results of
+ * each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @memberOf _
- * @category Utility
+ * @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the array of results.
* @example
*
- * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
- * // => [3, 6, 4]
+ * _.times(3, String);
+ * // => ['0', '1', '2']
*
- * _.times(3, function(n) {
- * mage.castSpell(n);
- * });
- * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
- *
- * _.times(3, function(n) {
- * this.cast(n);
- * }, mage);
- * // => also invokes `mage.castSpell(n)` three times
+ * _.times(4, _.constant(true));
+ * // => [true, true, true, true]
*/
- function times(n, iteratee, thisArg) {
- n = nativeFloor(n);
-
- // Exit early to avoid a JSC JIT bug in Safari 8
- // where `Array(0)` is treated as `Array(1)`.
- if (n < 1 || !nativeIsFinite(n)) {
+ function times(n, iteratee) {
+ n = toInteger(n);
+ if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
- var index = -1,
- result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
+ var index = MAX_ARRAY_LENGTH,
+ length = nativeMin(n, MAX_ARRAY_LENGTH);
+
+ iteratee = baseCastFunction(iteratee);
+ n -= MAX_ARRAY_LENGTH;
- iteratee = bindCallback(iteratee, thisArg, 1);
+ var result = baseTimes(length, iteratee);
while (++index < n) {
- if (index < MAX_ARRAY_LENGTH) {
- result[index] = iteratee(index);
- } else {
- iteratee(index);
- }
+ iteratee(index);
}
return result;
}
/**
- * Generates a unique ID. If `prefix` is provided the ID is appended to it.
+ * Converts `value` to a property path array.
*
* @static
* @memberOf _
- * @category Utility
- * @param {string} [prefix] The value to prefix the ID with.
+ * @category Util
+ * @param {*} value The value to convert.
+ * @returns {Array} Returns the new property path array.
+ * @example
+ *
+ * _.toPath('a.b.c');
+ * // => ['a', 'b', 'c']
+ *
+ * _.toPath('a[0].b.c');
+ * // => ['a', '0', 'b', 'c']
+ *
+ * var path = ['a', 'b', 'c'],
+ * newPath = _.toPath(path);
+ *
+ * console.log(newPath);
+ * // => ['a', 'b', 'c']
+ *
+ * console.log(path === newPath);
+ * // => false
+ */
+ function toPath(value) {
+ return isArray(value) ? arrayMap(value, String) : stringToPath(value);
+ }
+
+ /**
+ * Generates a unique ID. If `prefix` is given the ID is appended to it.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
*/
function uniqueId(prefix) {
var id = ++idCounter;
- return baseToString(prefix) + id;
+ return toString(prefix) + id;
}
/*------------------------------------------------------------------------*/
* @static
* @memberOf _
* @category Math
- * @param {number} augend The first number to add.
- * @param {number} addend The second number to add.
- * @returns {number} Returns the sum.
+ * @param {number} augend The first number in an addition.
+ * @param {number} addend The second number in an addition.
+ * @returns {number} Returns the total.
* @example
*
* _.add(6, 4);
* // => 10
*/
function add(augend, addend) {
- return (+augend || 0) + (+addend || 0);
+ var result;
+ if (augend === undefined && addend === undefined) {
+ return 0;
+ }
+ if (augend !== undefined) {
+ result = augend;
+ }
+ if (addend !== undefined) {
+ result = result === undefined ? addend : (result + addend);
+ }
+ return result;
}
/**
- * Calculates `n` rounded up to `precision`.
+ * Computes `number` rounded up to `precision`.
*
* @static
* @memberOf _
* @category Math
- * @param {number} n The number to round up.
+ * @param {number} number The number to round up.
* @param {number} [precision=0] The precision to round up to.
* @returns {number} Returns the rounded up number.
* @example
var ceil = createRound('ceil');
/**
- * Calculates `n` rounded down to `precision`.
+ * Computes `number` rounded down to `precision`.
*
* @static
* @memberOf _
* @category Math
- * @param {number} n The number to round down.
+ * @param {number} number The number to round down.
* @param {number} [precision=0] The precision to round down to.
* @returns {number} Returns the rounded down number.
* @example
var floor = createRound('floor');
/**
- * Gets the maximum value of `collection`. If `collection` is empty or falsey
- * `-Infinity` is returned. If an iteratee function is provided it's invoked
- * for each value in `collection` to generate the criterion by which the value
- * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
- * arguments: (value, index, collection).
- *
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
- *
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
- *
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * Computes the maximum value of `array`. If `array` is empty or falsey
+ * `undefined` is returned.
*
* @static
* @memberOf _
* @category Math
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [iteratee] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
* @example
*
* // => 8
*
* _.max([]);
- * // => -Infinity
+ * // => undefined
+ */
+ function max(array) {
+ return (array && array.length)
+ ? baseExtremum(array, identity, gt)
+ : undefined;
+ }
+
+ /**
+ * This method is like `_.max` except that it accepts `iteratee` which is
+ * invoked for each element in `array` to generate the criterion by which
+ * the value is ranked. The iteratee is invoked with one argument: (value).
*
- * var users = [
- * { 'user': 'barney', 'age': 36 },
- * { 'user': 'fred', 'age': 40 }
- * ];
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {Array} array The array to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {*} Returns the maximum value.
+ * @example
*
- * _.max(users, function(chr) {
- * return chr.age;
- * });
- * // => { 'user': 'fred', 'age': 40 }
+ * var objects = [{ 'n': 1 }, { 'n': 2 }];
*
- * // using the `_.property` callback shorthand
- * _.max(users, 'age');
- * // => { 'user': 'fred', 'age': 40 }
+ * _.maxBy(objects, function(o) { return o.n; });
+ * // => { 'n': 2 }
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.maxBy(objects, 'n');
+ * // => { 'n': 2 }
*/
- var max = createExtremum(gt, NEGATIVE_INFINITY);
+ function maxBy(array, iteratee) {
+ return (array && array.length)
+ ? baseExtremum(array, getIteratee(iteratee), gt)
+ : undefined;
+ }
/**
- * Gets the minimum value of `collection`. If `collection` is empty or falsey
- * `Infinity` is returned. If an iteratee function is provided it's invoked
- * for each value in `collection` to generate the criterion by which the value
- * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
- * arguments: (value, index, collection).
- *
- * If a property name is provided for `iteratee` the created `_.property`
- * style callback returns the property value of the given element.
+ * Computes the mean of the values in `array`.
*
- * If a value is also provided for `thisArg` the created `_.matchesProperty`
- * style callback returns `true` for elements that have a matching property
- * value, else `false`.
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {Array} array The array to iterate over.
+ * @returns {number} Returns the mean.
+ * @example
*
- * If an object is provided for `iteratee` the created `_.matches` style
- * callback returns `true` for elements that have the properties of the given
- * object, else `false`.
+ * _.mean([4, 2, 8, 6]);
+ * // => 5
+ */
+ function mean(array) {
+ return sum(array) / (array ? array.length : 0);
+ }
+
+ /**
+ * Computes the minimum value of `array`. If `array` is empty or falsey
+ * `undefined` is returned.
*
* @static
* @memberOf _
* @category Math
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [iteratee] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
* @example
*
* // => 2
*
* _.min([]);
- * // => Infinity
+ * // => undefined
+ */
+ function min(array) {
+ return (array && array.length)
+ ? baseExtremum(array, identity, lt)
+ : undefined;
+ }
+
+ /**
+ * This method is like `_.min` except that it accepts `iteratee` which is
+ * invoked for each element in `array` to generate the criterion by which
+ * the value is ranked. The iteratee is invoked with one argument: (value).
*
- * var users = [
- * { 'user': 'barney', 'age': 36 },
- * { 'user': 'fred', 'age': 40 }
- * ];
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {Array} array The array to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {*} Returns the minimum value.
+ * @example
*
- * _.min(users, function(chr) {
- * return chr.age;
- * });
- * // => { 'user': 'barney', 'age': 36 }
+ * var objects = [{ 'n': 1 }, { 'n': 2 }];
*
- * // using the `_.property` callback shorthand
- * _.min(users, 'age');
- * // => { 'user': 'barney', 'age': 36 }
+ * _.minBy(objects, function(o) { return o.n; });
+ * // => { 'n': 1 }
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.minBy(objects, 'n');
+ * // => { 'n': 1 }
*/
- var min = createExtremum(lt, POSITIVE_INFINITY);
+ function minBy(array, iteratee) {
+ return (array && array.length)
+ ? baseExtremum(array, getIteratee(iteratee), lt)
+ : undefined;
+ }
/**
- * Calculates `n` rounded to `precision`.
+ * Computes `number` rounded to `precision`.
*
* @static
* @memberOf _
* @category Math
- * @param {number} n The number to round.
+ * @param {number} number The number to round.
* @param {number} [precision=0] The precision to round to.
* @returns {number} Returns the rounded number.
* @example
var round = createRound('round');
/**
- * Gets the sum of the values in `collection`.
+ * Subtract two numbers.
*
* @static
* @memberOf _
* @category Math
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [iteratee] The function invoked per iteration.
- * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @param {number} minuend The first number in a subtraction.
+ * @param {number} subtrahend The second number in a subtraction.
+ * @returns {number} Returns the difference.
+ * @example
+ *
+ * _.subtract(6, 4);
+ * // => 2
+ */
+ function subtract(minuend, subtrahend) {
+ var result;
+ if (minuend === undefined && subtrahend === undefined) {
+ return 0;
+ }
+ if (minuend !== undefined) {
+ result = minuend;
+ }
+ if (subtrahend !== undefined) {
+ result = result === undefined ? subtrahend : (result - subtrahend);
+ }
+ return result;
+ }
+
+ /**
+ * Computes the sum of the values in `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
- * _.sum([4, 6]);
- * // => 10
+ * _.sum([4, 2, 8, 6]);
+ * // => 20
+ */
+ function sum(array) {
+ return (array && array.length)
+ ? baseSum(array, identity)
+ : 0;
+ }
+
+ /**
+ * This method is like `_.sum` except that it accepts `iteratee` which is
+ * invoked for each element in `array` to generate the value to be summed.
+ * The iteratee is invoked with one argument: (value).
*
- * _.sum({ 'a': 4, 'b': 6 });
- * // => 10
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {Array} array The array to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
+ * @returns {number} Returns the sum.
+ * @example
*
- * var objects = [
- * { 'n': 4 },
- * { 'n': 6 }
- * ];
+ * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
- * _.sum(objects, function(object) {
- * return object.n;
- * });
- * // => 10
+ * _.sumBy(objects, function(o) { return o.n; });
+ * // => 20
*
- * // using the `_.property` callback shorthand
- * _.sum(objects, 'n');
- * // => 10
+ * // The `_.property` iteratee shorthand.
+ * _.sumBy(objects, 'n');
+ * // => 20
*/
- function sum(collection, iteratee, thisArg) {
- if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
- iteratee = undefined;
- }
- iteratee = getCallback(iteratee, thisArg, 3);
- return iteratee.length == 1
- ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
- : baseSum(collection, iteratee);
+ function sumBy(array, iteratee) {
+ return (array && array.length)
+ ? baseSum(array, getIteratee(iteratee))
+ : 0;
}
/*------------------------------------------------------------------------*/
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
- // Add functions to the `Map` cache.
+ // Avoid inheriting from `Object.prototype` when possible.
+ Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto;
+
+ // Add functions to the `MapCache`.
+ MapCache.prototype.clear = mapClear;
MapCache.prototype['delete'] = mapDelete;
MapCache.prototype.get = mapGet;
MapCache.prototype.has = mapHas;
MapCache.prototype.set = mapSet;
- // Add functions to the `Set` cache.
+ // Add functions to the `SetCache`.
SetCache.prototype.push = cachePush;
+ // Add functions to the `Stack` cache.
+ Stack.prototype.clear = stackClear;
+ Stack.prototype['delete'] = stackDelete;
+ Stack.prototype.get = stackGet;
+ Stack.prototype.has = stackHas;
+ Stack.prototype.set = stackSet;
+
// Assign cache to `_.memoize`.
memoize.Cache = MapCache;
lodash.after = after;
lodash.ary = ary;
lodash.assign = assign;
+ lodash.assignIn = assignIn;
+ lodash.assignInWith = assignInWith;
+ lodash.assignWith = assignWith;
lodash.at = at;
lodash.before = before;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
- lodash.callback = callback;
+ lodash.castArray = castArray;
lodash.chain = chain;
lodash.chunk = chunk;
lodash.compact = compact;
+ lodash.concat = concat;
+ lodash.cond = cond;
+ lodash.conforms = conforms;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
+ lodash.differenceBy = differenceBy;
+ lodash.differenceWith = differenceWith;
lodash.drop = drop;
lodash.dropRight = dropRight;
lodash.dropRightWhile = dropRightWhile;
lodash.dropWhile = dropWhile;
lodash.fill = fill;
lodash.filter = filter;
+ lodash.flatMap = flatMap;
lodash.flatten = flatten;
lodash.flattenDeep = flattenDeep;
+ lodash.flattenDepth = flattenDepth;
+ lodash.flip = flip;
lodash.flow = flow;
lodash.flowRight = flowRight;
- lodash.forEach = forEach;
- lodash.forEachRight = forEachRight;
- lodash.forIn = forIn;
- lodash.forInRight = forInRight;
- lodash.forOwn = forOwn;
- lodash.forOwnRight = forOwnRight;
+ lodash.fromPairs = fromPairs;
lodash.functions = functions;
+ lodash.functionsIn = functionsIn;
lodash.groupBy = groupBy;
- lodash.indexBy = indexBy;
lodash.initial = initial;
lodash.intersection = intersection;
+ lodash.intersectionBy = intersectionBy;
+ lodash.intersectionWith = intersectionWith;
lodash.invert = invert;
- lodash.invoke = invoke;
+ lodash.invertBy = invertBy;
+ lodash.invokeMap = invokeMap;
+ lodash.iteratee = iteratee;
+ lodash.keyBy = keyBy;
lodash.keys = keys;
lodash.keysIn = keysIn;
lodash.map = map;
lodash.matchesProperty = matchesProperty;
lodash.memoize = memoize;
lodash.merge = merge;
+ lodash.mergeWith = mergeWith;
lodash.method = method;
lodash.methodOf = methodOf;
lodash.mixin = mixin;
- lodash.modArgs = modArgs;
lodash.negate = negate;
+ lodash.nthArg = nthArg;
lodash.omit = omit;
+ lodash.omitBy = omitBy;
lodash.once = once;
- lodash.pairs = pairs;
+ lodash.orderBy = orderBy;
+ lodash.over = over;
+ lodash.overArgs = overArgs;
+ lodash.overEvery = overEvery;
+ lodash.overSome = overSome;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.partition = partition;
lodash.pick = pick;
- lodash.pluck = pluck;
+ lodash.pickBy = pickBy;
lodash.property = property;
lodash.propertyOf = propertyOf;
lodash.pull = pull;
+ lodash.pullAll = pullAll;
+ lodash.pullAllBy = pullAllBy;
lodash.pullAt = pullAt;
lodash.range = range;
+ lodash.rangeRight = rangeRight;
lodash.rearg = rearg;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
- lodash.restParam = restParam;
+ lodash.reverse = reverse;
+ lodash.sampleSize = sampleSize;
lodash.set = set;
+ lodash.setWith = setWith;
lodash.shuffle = shuffle;
lodash.slice = slice;
lodash.sortBy = sortBy;
- lodash.sortByAll = sortByAll;
- lodash.sortByOrder = sortByOrder;
+ lodash.sortedUniq = sortedUniq;
+ lodash.sortedUniqBy = sortedUniqBy;
+ lodash.split = split;
lodash.spread = spread;
+ lodash.tail = tail;
lodash.take = take;
lodash.takeRight = takeRight;
lodash.takeRightWhile = takeRightWhile;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.thru = thru;
- lodash.times = times;
lodash.toArray = toArray;
+ lodash.toPairs = toPairs;
+ lodash.toPairsIn = toPairsIn;
+ lodash.toPath = toPath;
lodash.toPlainObject = toPlainObject;
lodash.transform = transform;
+ lodash.unary = unary;
lodash.union = union;
+ lodash.unionBy = unionBy;
+ lodash.unionWith = unionWith;
lodash.uniq = uniq;
+ lodash.uniqBy = uniqBy;
+ lodash.uniqWith = uniqWith;
+ lodash.unset = unset;
lodash.unzip = unzip;
lodash.unzipWith = unzipWith;
lodash.values = values;
lodash.valuesIn = valuesIn;
- lodash.where = where;
lodash.without = without;
+ lodash.words = words;
lodash.wrap = wrap;
lodash.xor = xor;
+ lodash.xorBy = xorBy;
+ lodash.xorWith = xorWith;
lodash.zip = zip;
lodash.zipObject = zipObject;
+ lodash.zipObjectDeep = zipObjectDeep;
lodash.zipWith = zipWith;
// Add aliases.
- lodash.backflow = flowRight;
- lodash.collect = map;
- lodash.compose = flowRight;
- lodash.each = forEach;
- lodash.eachRight = forEachRight;
- lodash.extend = assign;
- lodash.iteratee = callback;
- lodash.methods = functions;
- lodash.object = zipObject;
- lodash.select = filter;
- lodash.tail = rest;
- lodash.unique = uniq;
+ lodash.extend = assignIn;
+ lodash.extendWith = assignInWith;
// Add functions to `lodash.prototype`.
mixin(lodash, lodash);
lodash.camelCase = camelCase;
lodash.capitalize = capitalize;
lodash.ceil = ceil;
+ lodash.clamp = clamp;
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
+ lodash.cloneDeepWith = cloneDeepWith;
+ lodash.cloneWith = cloneWith;
lodash.deburr = deburr;
lodash.endsWith = endsWith;
+ lodash.eq = eq;
lodash.escape = escape;
lodash.escapeRegExp = escapeRegExp;
lodash.every = every;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
- lodash.findWhere = findWhere;
- lodash.first = first;
lodash.floor = floor;
+ lodash.forEach = forEach;
+ lodash.forEachRight = forEachRight;
+ lodash.forIn = forIn;
+ lodash.forInRight = forInRight;
+ lodash.forOwn = forOwn;
+ lodash.forOwnRight = forOwnRight;
lodash.get = get;
lodash.gt = gt;
lodash.gte = gte;
lodash.has = has;
+ lodash.hasIn = hasIn;
+ lodash.head = head;
lodash.identity = identity;
lodash.includes = includes;
lodash.indexOf = indexOf;
lodash.inRange = inRange;
+ lodash.invoke = invoke;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
+ lodash.isArrayBuffer = isArrayBuffer;
+ lodash.isArrayLike = isArrayLike;
+ lodash.isArrayLikeObject = isArrayLikeObject;
lodash.isBoolean = isBoolean;
+ lodash.isBuffer = isBuffer;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
+ lodash.isEqualWith = isEqualWith;
lodash.isError = isError;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
+ lodash.isInteger = isInteger;
+ lodash.isLength = isLength;
+ lodash.isMap = isMap;
lodash.isMatch = isMatch;
+ lodash.isMatchWith = isMatchWith;
lodash.isNaN = isNaN;
lodash.isNative = isNative;
+ lodash.isNil = isNil;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
+ lodash.isObjectLike = isObjectLike;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
+ lodash.isSafeInteger = isSafeInteger;
+ lodash.isSet = isSet;
lodash.isString = isString;
+ lodash.isSymbol = isSymbol;
lodash.isTypedArray = isTypedArray;
lodash.isUndefined = isUndefined;
+ lodash.isWeakMap = isWeakMap;
+ lodash.isWeakSet = isWeakSet;
+ lodash.join = join;
lodash.kebabCase = kebabCase;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
+ lodash.lowerCase = lowerCase;
+ lodash.lowerFirst = lowerFirst;
lodash.lt = lt;
lodash.lte = lte;
lodash.max = max;
+ lodash.maxBy = maxBy;
+ lodash.mean = mean;
lodash.min = min;
+ lodash.minBy = minBy;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.pad = pad;
- lodash.padLeft = padLeft;
- lodash.padRight = padRight;
+ lodash.padEnd = padEnd;
+ lodash.padStart = padStart;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.repeat = repeat;
+ lodash.replace = replace;
lodash.result = result;
lodash.round = round;
lodash.runInContext = runInContext;
+ lodash.sample = sample;
lodash.size = size;
lodash.snakeCase = snakeCase;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
+ lodash.sortedIndexBy = sortedIndexBy;
+ lodash.sortedIndexOf = sortedIndexOf;
lodash.sortedLastIndex = sortedLastIndex;
+ lodash.sortedLastIndexBy = sortedLastIndexBy;
+ lodash.sortedLastIndexOf = sortedLastIndexOf;
lodash.startCase = startCase;
lodash.startsWith = startsWith;
+ lodash.subtract = subtract;
lodash.sum = sum;
+ lodash.sumBy = sumBy;
lodash.template = template;
+ lodash.times = times;
+ lodash.toInteger = toInteger;
+ lodash.toLength = toLength;
+ lodash.toLower = toLower;
+ lodash.toNumber = toNumber;
+ lodash.toSafeInteger = toSafeInteger;
+ lodash.toString = toString;
+ lodash.toUpper = toUpper;
lodash.trim = trim;
- lodash.trimLeft = trimLeft;
- lodash.trimRight = trimRight;
- lodash.trunc = trunc;
+ lodash.trimEnd = trimEnd;
+ lodash.trimStart = trimStart;
+ lodash.truncate = truncate;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
- lodash.words = words;
+ lodash.upperCase = upperCase;
+ lodash.upperFirst = upperFirst;
// Add aliases.
- lodash.all = every;
- lodash.any = some;
- lodash.contains = includes;
- lodash.eq = isEqual;
- lodash.detect = find;
- lodash.foldl = reduce;
- lodash.foldr = reduceRight;
- lodash.head = first;
- lodash.include = includes;
- lodash.inject = reduce;
+ lodash.each = forEach;
+ lodash.eachRight = forEachRight;
+ lodash.first = head;
mixin(lodash, (function() {
var source = {};
baseForOwn(lodash, function(func, methodName) {
- if (!lodash.prototype[methodName]) {
+ if (!hasOwnProperty.call(lodash.prototype, methodName)) {
source[methodName] = func;
}
});
return source;
- }()), false);
-
- /*------------------------------------------------------------------------*/
-
- // Add functions capable of returning wrapped and unwrapped values when chaining.
- lodash.sample = sample;
-
- lodash.prototype.sample = function(n) {
- if (!this.__chain__ && n == null) {
- return sample(this.value());
- }
- return this.thru(function(value) {
- return sample(value, n);
- });
- };
+ }()), { 'chain': false });
/*------------------------------------------------------------------------*/
*
* @static
* @memberOf _
- * @type string
+ * @type {string}
*/
lodash.VERSION = VERSION;
if (filtered && !index) {
return new LazyWrapper(this);
}
- n = n == null ? 1 : nativeMax(nativeFloor(n) || 0, 0);
+ n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
var result = this.clone();
if (filtered) {
- result.__takeCount__ = nativeMin(result.__takeCount__, n);
+ result.__takeCount__ = nativeMin(n, result.__takeCount__);
} else {
- result.__views__.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
+ result.__views__.push({
+ 'size': nativeMin(n, MAX_ARRAY_LENGTH),
+ 'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
+ });
}
return result;
};
// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
var type = index + 1,
- isFilter = type != LAZY_MAP_FLAG;
+ isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
- LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
+ LazyWrapper.prototype[methodName] = function(iteratee) {
var result = this.clone();
- result.__iteratees__.push({ 'iteratee': getCallback(iteratee, thisArg, 1), 'type': type });
+ result.__iteratees__.push({
+ 'iteratee': getIteratee(iteratee, 3),
+ 'type': type
+ });
result.__filtered__ = result.__filtered__ || isFilter;
return result;
};
});
- // Add `LazyWrapper` methods for `_.first` and `_.last`.
- arrayEach(['first', 'last'], function(methodName, index) {
+ // Add `LazyWrapper` methods for `_.head` and `_.last`.
+ arrayEach(['head', 'last'], function(methodName, index) {
var takeName = 'take' + (index ? 'Right' : '');
LazyWrapper.prototype[methodName] = function() {
};
});
- // Add `LazyWrapper` methods for `_.initial` and `_.rest`.
- arrayEach(['initial', 'rest'], function(methodName, index) {
+ // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
+ arrayEach(['initial', 'tail'], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
};
});
- // Add `LazyWrapper` methods for `_.pluck` and `_.where`.
- arrayEach(['pluck', 'where'], function(methodName, index) {
- var operationName = index ? 'filter' : 'map',
- createCallback = index ? baseMatches : property;
-
- LazyWrapper.prototype[methodName] = function(value) {
- return this[operationName](createCallback(value));
- };
- });
-
LazyWrapper.prototype.compact = function() {
return this.filter(identity);
};
- LazyWrapper.prototype.reject = function(predicate, thisArg) {
- predicate = getCallback(predicate, thisArg, 1);
+ LazyWrapper.prototype.find = function(predicate) {
+ return this.filter(predicate).head();
+ };
+
+ LazyWrapper.prototype.findLast = function(predicate) {
+ return this.reverse().find(predicate);
+ };
+
+ LazyWrapper.prototype.invokeMap = rest(function(path, args) {
+ if (typeof path == 'function') {
+ return new LazyWrapper(this);
+ }
+ return this.map(function(value) {
+ return baseInvoke(value, path, args);
+ });
+ });
+
+ LazyWrapper.prototype.reject = function(predicate) {
+ predicate = getIteratee(predicate, 3);
return this.filter(function(value) {
return !predicate(value);
});
};
LazyWrapper.prototype.slice = function(start, end) {
- start = start == null ? 0 : (+start || 0);
+ start = toInteger(start);
var result = this;
if (result.__filtered__ && (start > 0 || end < 0)) {
result = result.drop(start);
}
if (end !== undefined) {
- end = (+end || 0);
+ end = toInteger(end);
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
}
return result;
};
- LazyWrapper.prototype.takeRightWhile = function(predicate, thisArg) {
- return this.reverse().takeWhile(predicate, thisArg).reverse();
+ LazyWrapper.prototype.takeRightWhile = function(predicate) {
+ return this.reverse().takeWhile(predicate).reverse();
};
LazyWrapper.prototype.toArray = function() {
- return this.take(POSITIVE_INFINITY);
+ return this.take(MAX_ARRAY_LENGTH);
};
// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
- var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
- retUnwrapped = /^(?:first|last)$/.test(methodName),
- lodashFunc = lodash[retUnwrapped ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName];
+ var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
+ isTaker = /^(?:head|last)$/.test(methodName),
+ lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
+ retUnwrapped = isTaker || /^find/.test(methodName);
if (!lodashFunc) {
return;
}
lodash.prototype[methodName] = function() {
- var args = retUnwrapped ? [1] : arguments,
- chainAll = this.__chain__,
- value = this.__wrapped__,
- isHybrid = !!this.__actions__.length,
+ var value = this.__wrapped__,
+ args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
+ var interceptor = function(value) {
+ var result = lodashFunc.apply(lodash, arrayPush([value], args));
+ return (isTaker && chainAll) ? result[0] : result;
+ };
+
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
- var interceptor = function(value) {
- return (retUnwrapped && chainAll)
- ? lodashFunc(value, 1)[0]
- : lodashFunc.apply(undefined, arrayPush([value], args));
- };
-
- var action = { 'func': thru, 'args': [interceptor], 'thisArg': undefined },
+ var chainAll = this.__chain__,
+ isHybrid = !!this.__actions__.length,
+ isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
- if (retUnwrapped && !chainAll) {
- if (onlyLazy) {
- value = value.clone();
- value.__actions__.push(action);
- return func.call(value);
- }
- return lodashFunc.call(undefined, this.value())[0];
- }
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
- result.__actions__.push(action);
+ result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
- return this.thru(interceptor);
+ if (isUnwrapped && onlyLazy) {
+ return func.apply(this, args);
+ }
+ result = this.thru(interceptor);
+ return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
};
});
// Add `Array` and `String` methods to `lodash.prototype`.
- arrayEach(['join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
- var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
+ arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
+ var func = arrayProto[methodName],
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
- retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
+ retUnwrapped = /^(?:pop|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
}
});
- realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }];
+ realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{
+ 'name': 'wrapper',
+ 'func': undefined
+ }];
// Add functions to the lazy wrapper.
LazyWrapper.prototype.clone = lazyClone;
LazyWrapper.prototype.value = lazyValue;
// Add chaining functions to the `lodash` wrapper.
+ lodash.prototype.at = wrapperAt;
lodash.prototype.chain = wrapperChain;
lodash.prototype.commit = wrapperCommit;
- lodash.prototype.concat = wrapperConcat;
+ lodash.prototype.flatMap = wrapperFlatMap;
+ lodash.prototype.next = wrapperNext;
lodash.prototype.plant = wrapperPlant;
lodash.prototype.reverse = wrapperReverse;
- lodash.prototype.toString = wrapperToString;
- lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
-
- // Add function aliases to the `lodash` wrapper.
- lodash.prototype.collect = lodash.prototype.map;
- lodash.prototype.head = lodash.prototype.first;
- lodash.prototype.select = lodash.prototype.filter;
- lodash.prototype.tail = lodash.prototype.rest;
+ lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
+ if (iteratorSymbol) {
+ lodash.prototype[iteratorSymbol] = wrapperToIterator;
+ }
return lodash;
}
// Export lodash.
var _ = runInContext();
+ // Expose lodash on the free variable `window` or `self` when available. This
+ // prevents errors in cases where lodash is loaded by a script tag in the presence
+ // of an AMD loader. See http://requirejs.org/docs/errors.html#mismatch for more details.
+ (freeWindow || freeSelf || {})._ = _;
+
// Some AMD build optimizers like r.js check for condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
- // Expose lodash to the global object when an AMD loader is present to avoid
- // errors in cases where lodash is loaded by a script tag and not intended
- // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
- // more details.
- root._ = _;
-
// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
}
// Check for `exports` after `define` in case a build optimizer adds an `exports` object.
else if (freeExports && freeModule) {
- // Export for Node.js or RingoJS.
+ // Export for Node.js.
if (moduleExports) {
(freeModule.exports = _)._ = _;
}
- // Export for Rhino with CommonJS support.
- else {
- freeExports._ = _;
- }
+ // Export for CommonJS support.
+ freeExports._ = _;
}
else {
- // Export for a browser or Rhino.
+ // Export to the global object.
root._ = _;
}
}.call(this));