diff --git a/README.md b/README.md index 4d1258e05..5907769d5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# lodash v3.6.0 +# lodash v3.7.0 The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash](https://lodash.com/) exported as [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) modules. @@ -10,6 +10,13 @@ $ lodash modern exports=amd -d -o ./main.js ## Installation +Using bower or volo: + +```bash +$ bower i lodash#3.7.0-amd +$ volo add lodash/3.7.0-amd +``` + Defining a build as `'lodash'`. ```js diff --git a/array/intersection.js b/array/intersection.js index fda10ebeb..f4c3633b1 100644 --- a/array/intersection.js +++ b/array/intersection.js @@ -23,7 +23,8 @@ define(['../internal/baseIndexOf', '../internal/cacheIndexOf', '../internal/crea argsLength = arguments.length, caches = [], indexOf = baseIndexOf, - isCommon = true; + isCommon = true, + result = []; while (++argsIndex < argsLength) { var value = arguments[argsIndex]; @@ -33,10 +34,12 @@ define(['../internal/baseIndexOf', '../internal/cacheIndexOf', '../internal/crea } } argsLength = args.length; + if (argsLength < 2) { + return result; + } var array = args[0], index = -1, length = array ? array.length : 0, - result = [], seen = caches[0]; outer: diff --git a/array/pullAt.js b/array/pullAt.js index 58ba6e175..837ee4410 100644 --- a/array/pullAt.js +++ b/array/pullAt.js @@ -1,10 +1,4 @@ -define(['../internal/baseAt', '../internal/baseCompareAscending', '../internal/baseFlatten', '../internal/isIndex', '../function/restParam'], function(baseAt, baseCompareAscending, baseFlatten, isIndex, restParam) { - - /** Used for native method references. */ - var arrayProto = Array.prototype; - - /** Native method references. */ - var splice = arrayProto.splice; +define(['../internal/baseAt', '../internal/baseCompareAscending', '../internal/baseFlatten', '../internal/basePullAt', '../function/restParam'], function(baseAt, baseCompareAscending, baseFlatten, basePullAt, restParam) { /** * Removes elements from `array` corresponding to the given indexes and returns @@ -35,17 +29,8 @@ define(['../internal/baseAt', '../internal/baseCompareAscending', '../internal/b array || (array = []); indexes = baseFlatten(indexes); - var length = indexes.length, - result = baseAt(array, indexes); - - indexes.sort(baseCompareAscending); - while (length--) { - var index = parseFloat(indexes[length]); - if (index != previous && isIndex(index)) { - var previous = index; - splice.call(array, index, 1); - } - } + var result = baseAt(array, indexes); + basePullAt(array, indexes.sort(baseCompareAscending)); return result; }); diff --git a/array/remove.js b/array/remove.js index 60dac434e..2c9e39e07 100644 --- a/array/remove.js +++ b/array/remove.js @@ -1,10 +1,4 @@ -define(['../internal/baseCallback'], function(baseCallback) { - - /** Used for native method references. */ - var arrayProto = Array.prototype; - - /** Native method references. */ - var splice = arrayProto.splice; +define(['../internal/baseCallback', '../internal/basePullAt'], function(baseCallback, basePullAt) { /** * Removes all elements from `array` that `predicate` returns truthy for @@ -46,19 +40,23 @@ define(['../internal/baseCallback'], function(baseCallback) { * // => [2, 4] */ function remove(array, predicate, thisArg) { + var result = []; + if (!(array && array.length)) { + return result; + } var index = -1, - length = array ? array.length : 0, - result = []; + indexes = [], + length = array.length; predicate = baseCallback(predicate, thisArg, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); - splice.call(array, index--, 1); - length--; + indexes.push(index); } } + basePullAt(array, indexes); return result; } diff --git a/array/slice.js b/array/slice.js index 5a0643566..412d7eb32 100644 --- a/array/slice.js +++ b/array/slice.js @@ -3,7 +3,7 @@ define(['../internal/baseSlice', '../internal/isIterateeCall'], function(baseSli /** * Creates a slice of `array` from `start` up to, but not including, `end`. * - * **Note:** This function is used instead of `Array#slice` to support node + * **Note:** This method is used instead of `Array#slice` to support node * lists in IE < 9 and to ensure dense arrays are returned. * * @static diff --git a/array/uniq.js b/array/uniq.js index ff6f96d8e..554599168 100644 --- a/array/uniq.js +++ b/array/uniq.js @@ -1,12 +1,13 @@ define(['../internal/baseCallback', '../internal/baseUniq', '../internal/isIterateeCall', '../internal/sortedUniq'], function(baseCallback, baseUniq, isIterateeCall, sortedUniq) { /** - * Creates a duplicate-value-free version of an array using `SameValueZero` - * for equality comparisons. Providing `true` for `isSorted` performs a faster - * search algorithm for sorted arrays. If an iteratee function is provided it - * is invoked for each value 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). + * Creates a duplicate-free version of an array, using `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 is 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). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. @@ -34,8 +35,8 @@ define(['../internal/baseCallback', '../internal/baseUniq', '../internal/isItera * @returns {Array} Returns the new duplicate-value-free array. * @example * - * _.uniq([1, 2, 1]); - * // => [1, 2] + * _.uniq([2, 1, 2]); + * // => [2, 1] * * // using `isSorted` * _.uniq([1, 1, 2], true); diff --git a/array/unzip.js b/array/unzip.js index 2ccc4180d..2fe376397 100644 --- a/array/unzip.js +++ b/array/unzip.js @@ -1,7 +1,4 @@ -define(['../internal/arrayMap', '../internal/arrayMax', '../internal/baseProperty'], function(arrayMap, arrayMax, baseProperty) { - - /** Used to the length of n-tuples for `_.unzip`. */ - var getLength = baseProperty('length'); +define(['../internal/arrayMap', '../internal/arrayMax', '../internal/baseProperty', '../internal/getLength'], function(arrayMap, arrayMax, baseProperty, getLength) { /** * This method is like `_.zip` except that it accepts an array of grouped diff --git a/chain/lodash.js b/chain/lodash.js index fadffba7d..581a643ed 100644 --- a/chain/lodash.js +++ b/chain/lodash.js @@ -45,8 +45,8 @@ define(['../internal/LazyWrapper', '../internal/LodashWrapper', '../internal/bas * `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`, * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`, * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`, - * `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, `merge`, - * `mixin`, `negate`, `noop`, `omit`, `once`, `pairs`, `partial`, `partialRight`, + * `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, + * `merge`, `mixin`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`, * `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `sortByOrder`, `splice`, @@ -60,15 +60,15 @@ define(['../internal/LazyWrapper', '../internal/LodashWrapper', '../internal/bas * `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, * `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `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`, `max`, `min`, - * `noConflict`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, - * `random`, `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`, - * `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, - * `startCase`, `startsWith`, `sum`, `template`, `trim`, `trimLeft`, - * `trimRight`, `trunc`, `unescape`, `uniqueId`, `value`, and `words` + * `isBoolean`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, `isFinite` + * `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, + * `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, + * `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`, `noConflict`, + * `noop`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, + * `reduce`, `reduceRight`, `repeat`, `result`, `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. @@ -83,8 +83,8 @@ define(['../internal/LazyWrapper', '../internal/LodashWrapper', '../internal/bas * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value - * wrapped.reduce(function(sum, n) { - * return sum + n; + * wrapped.reduce(function(total, n) { + * return total + n; * }); * // => 6 * diff --git a/collection/at.js b/collection/at.js index 983344d7f..8436c8f4e 100644 --- a/collection/at.js +++ b/collection/at.js @@ -1,4 +1,4 @@ -define(['../internal/baseAt', '../internal/baseFlatten', '../internal/isLength', '../function/restParam', '../internal/toIterable'], function(baseAt, baseFlatten, isLength, restParam, toIterable) { +define(['../internal/baseAt', '../internal/baseFlatten', '../internal/getLength', '../internal/isLength', '../function/restParam', '../internal/toIterable'], function(baseAt, baseFlatten, getLength, isLength, restParam, toIterable) { /** * Creates an array of elements corresponding to the given keys, or indexes, @@ -21,7 +21,7 @@ define(['../internal/baseAt', '../internal/baseFlatten', '../internal/isLength', * // => ['barney', 'pebbles'] */ var at = restParam(function(collection, props) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; if (isLength(length)) { collection = toIterable(collection); } diff --git a/collection/every.js b/collection/every.js index bce32fbb2..6b2a4dbfa 100644 --- a/collection/every.js +++ b/collection/every.js @@ -1,5 +1,8 @@ define(['../internal/arrayEvery', '../internal/baseCallback', '../internal/baseEvery', '../lang/isArray', '../internal/isIterateeCall'], function(arrayEvery, baseCallback, baseEvery, isArray, isIterateeCall) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * The predicate is bound to `thisArg` and invoked with three arguments: @@ -53,7 +56,7 @@ define(['../internal/arrayEvery', '../internal/baseCallback', '../internal/baseE if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } - if (typeof predicate != 'function' || typeof thisArg != 'undefined') { + if (typeof predicate != 'function' || thisArg !== undefined) { predicate = baseCallback(predicate, thisArg, 3); } return func(collection, predicate); diff --git a/collection/forEach.js b/collection/forEach.js index 3921636d4..5c44cca5a 100644 --- a/collection/forEach.js +++ b/collection/forEach.js @@ -3,10 +3,10 @@ define(['../internal/arrayEach', '../internal/baseEach', '../internal/createForE /** * 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). Iterator functions may exit iteration early + * (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 + * **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. * diff --git a/collection/includes.js b/collection/includes.js index 0e65007fe..76b28c6ee 100644 --- a/collection/includes.js +++ b/collection/includes.js @@ -1,4 +1,4 @@ -define(['../internal/baseIndexOf', '../lang/isArray', '../internal/isIterateeCall', '../internal/isLength', '../lang/isString', '../object/values'], function(baseIndexOf, isArray, isIterateeCall, isLength, isString, values) { +define(['../internal/baseIndexOf', '../internal/getLength', '../lang/isArray', '../internal/isIterateeCall', '../internal/isLength', '../lang/isString', '../object/values'], function(baseIndexOf, getLength, isArray, isIterateeCall, isLength, isString, values) { /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; @@ -36,7 +36,7 @@ define(['../internal/baseIndexOf', '../lang/isArray', '../internal/isIterateeCal * // => true */ function includes(collection, target, fromIndex, guard) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; if (!isLength(length)) { collection = values(collection); length = collection.length; diff --git a/collection/invoke.js b/collection/invoke.js index 9944cae8c..6ae2abd1b 100644 --- a/collection/invoke.js +++ b/collection/invoke.js @@ -1,19 +1,16 @@ -define(['../internal/baseEach', '../internal/isLength', '../function/restParam'], function(baseEach, isLength, restParam) { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; +define(['../internal/baseEach', '../internal/getLength', '../internal/invokePath', '../internal/isKey', '../internal/isLength', '../function/restParam'], function(baseEach, getLength, invokePath, isKey, isLength, restParam) { /** - * Invokes the method named by `methodName` on 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 is invoked for, and `this` bound to, each element in `collection`. + * Invokes the method at `path` on 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 is + * invoked for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|string} methodName The name of the method to invoke or + * @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. * @returns {Array} Returns the array of results. @@ -25,15 +22,16 @@ define(['../internal/baseEach', '../internal/isLength', '../function/restParam'] * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ - var invoke = restParam(function(collection, methodName, args) { + var invoke = restParam(function(collection, path, args) { var index = -1, - isFunc = typeof methodName == 'function', - length = collection ? collection.length : 0, + isFunc = typeof path == 'function', + isProp = isKey(path), + length = getLength(collection), result = isLength(length) ? Array(length) : []; baseEach(collection, function(value) { - var func = isFunc ? methodName : (value != null && value[methodName]); - result[++index] = func ? func.apply(value, args) : undefined; + var func = isFunc ? path : (isProp && value != null && value[path]); + result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); }); return result; }); diff --git a/collection/map.js b/collection/map.js index 6d58970c4..dfebf9f6c 100644 --- a/collection/map.js +++ b/collection/map.js @@ -32,7 +32,6 @@ define(['../internal/arrayMap', '../internal/baseCallback', '../internal/baseMap * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. - * create a `_.property` or `_.matches` style callback respectively. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new mapped array. * @example diff --git a/collection/pluck.js b/collection/pluck.js index a4c6e9ef9..bcad0dcc2 100644 --- a/collection/pluck.js +++ b/collection/pluck.js @@ -1,13 +1,13 @@ -define(['../internal/baseProperty', './map'], function(baseProperty, map) { +define(['./map', '../utility/property'], function(map, property) { /** - * Gets the value of `key` from all elements in `collection`. + * Gets the property value of `path` from all elements in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. - * @param {string} key The key of the property to pluck. + * @param {Array|string} path The path of the property to pluck. * @returns {Array} Returns the property values. * @example * @@ -23,8 +23,8 @@ define(['../internal/baseProperty', './map'], function(baseProperty, map) { * _.pluck(userIndex, 'age'); * // => [36, 40] (iteration order is not guaranteed) */ - function pluck(collection, key) { - return map(collection, baseProperty(key)); + function pluck(collection, path) { + return map(collection, property(path)); } return pluck; diff --git a/collection/reduce.js b/collection/reduce.js index 5f310b576..300699cfa 100644 --- a/collection/reduce.js +++ b/collection/reduce.js @@ -25,8 +25,8 @@ define(['../internal/arrayReduce', '../internal/baseEach', '../internal/createRe * @returns {*} Returns the accumulated value. * @example * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; + * _.reduce([1, 2], function(total, n) { + * return total + n; * }); * // => 3 * diff --git a/collection/size.js b/collection/size.js index d47800195..c614e27d7 100644 --- a/collection/size.js +++ b/collection/size.js @@ -1,4 +1,4 @@ -define(['../internal/isLength', '../object/keys'], function(isLength, keys) { +define(['../internal/getLength', '../internal/isLength', '../object/keys'], function(getLength, isLength, keys) { /** * Gets the size of `collection` by returning its length for array-like @@ -21,7 +21,7 @@ define(['../internal/isLength', '../object/keys'], function(isLength, keys) { * // => 7 */ function size(collection) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; return isLength(length) ? length : keys(collection).length; } diff --git a/collection/some.js b/collection/some.js index 5d31b5b3c..18f4308e7 100644 --- a/collection/some.js +++ b/collection/some.js @@ -1,5 +1,8 @@ define(['../internal/arraySome', '../internal/baseCallback', '../internal/baseSome', '../lang/isArray', '../internal/isIterateeCall'], function(arraySome, baseCallback, baseSome, isArray, isIterateeCall) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * 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 @@ -54,7 +57,7 @@ define(['../internal/arraySome', '../internal/baseCallback', '../internal/baseSo if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } - if (typeof predicate != 'function' || typeof thisArg != 'undefined') { + if (typeof predicate != 'function' || thisArg !== undefined) { predicate = baseCallback(predicate, thisArg, 3); } return func(collection, predicate); diff --git a/collection/sortBy.js b/collection/sortBy.js index 3deb387ac..0958b118b 100644 --- a/collection/sortBy.js +++ b/collection/sortBy.js @@ -1,4 +1,4 @@ -define(['../internal/baseCallback', '../internal/baseEach', '../internal/baseSortBy', '../internal/compareAscending', '../internal/isIterateeCall', '../internal/isLength'], function(baseCallback, baseEach, baseSortBy, compareAscending, isIterateeCall, isLength) { +define(['../internal/baseCallback', '../internal/baseMap', '../internal/baseSortBy', '../internal/compareAscending', '../internal/isIterateeCall'], function(baseCallback, baseMap, baseSortBy, compareAscending, isIterateeCall) { /** * Creates an array of elements, sorted in ascending order by the results of @@ -22,9 +22,8 @@ define(['../internal/baseCallback', '../internal/baseEach', '../internal/baseSor * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. - * @param {Array|Function|Object|string} [iteratee=_.identity] The function - * invoked per iteration. If a property name or an object is provided it is - * used to create a `_.property` or `_.matches` style callback respectively. + * @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 @@ -53,16 +52,14 @@ define(['../internal/baseCallback', '../internal/baseEach', '../internal/baseSor if (collection == null) { return []; } - var index = -1, - length = collection.length, - result = isLength(length) ? Array(length) : []; - if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } + var index = -1; iteratee = baseCallback(iteratee, thisArg, 3); - baseEach(collection, function(value, key, collection) { - result[++index] = { 'criteria': iteratee(value, key, collection), 'index': index, 'value': value }; + + var result = baseMap(collection, function(value, key, collection) { + return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; }); return baseSortBy(result, compareAscending); } diff --git a/collection/sortByAll.js b/collection/sortByAll.js index 7f42de4a9..1184b98ef 100644 --- a/collection/sortByAll.js +++ b/collection/sortByAll.js @@ -1,47 +1,50 @@ -define(['../internal/baseFlatten', '../internal/baseSortByOrder', '../internal/isIterateeCall'], function(baseFlatten, baseSortByOrder, isIterateeCall) { +define(['../internal/baseFlatten', '../internal/baseSortByOrder', '../internal/isIterateeCall', '../function/restParam'], function(baseFlatten, baseSortByOrder, isIterateeCall, restParam) { /** - * This method is like `_.sortBy` except that it sorts by property names - * instead of an iteratee function. + * 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 {...(string|string[])} props The property names to sort by, - * specified as individual property names or arrays of property names. + * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees + * The iteratees to sort by, specified as individual values or arrays of values. * @returns {Array} Returns the new sorted array. * @example * * var users = [ + * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 26 }, - * { 'user': 'fred', 'age': 30 } + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 34 } * ]; * * _.map(_.sortByAll(users, ['user', 'age']), _.values); - * // => [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] + * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] + * + * _.map(_.sortByAll(users, 'user', function(chr) { + * return Math.floor(chr.age / 10); + * }), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ - function sortByAll() { - var args = arguments, - collection = args[0], - guard = args[3], - index = 0, - length = args.length - 1; - + var sortByAll = restParam(function(collection, iteratees) { if (collection == null) { return []; } - var props = Array(length); - while (index < length) { - props[index] = args[++index]; + var guard = iteratees[2]; + if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { + iteratees.length = 1; } - if (guard && isIterateeCall(args[1], args[2], guard)) { - props = args[1]; - } - return baseSortByOrder(collection, baseFlatten(props), []); - } + return baseSortByOrder(collection, baseFlatten(iteratees), []); + }); return sortByAll; }); diff --git a/collection/sortByOrder.js b/collection/sortByOrder.js index 7e47b56a0..c8899a600 100644 --- a/collection/sortByOrder.js +++ b/collection/sortByOrder.js @@ -2,45 +2,52 @@ define(['../internal/baseSortByOrder', '../lang/isArray', '../internal/isIterate /** * This method is like `_.sortByAll` except that it allows specifying the - * sort orders of the property names to sort by. A truthy value in `orders` - * will sort the corresponding property name in ascending order while a - * falsey value will sort it in descending order. + * sort orders of the iteratees to sort by. A truthy value in `orders` will + * sort the corresponding property name in ascending order while a falsey + * value will sort it in descending order. + * + * 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 {string[]} props The property names to sort by. - * @param {boolean[]} orders The sort orders of `props`. + * @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': 'barney', 'age': 26 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 30 } + * { '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'], [true, false]), _.values); - * // => [['barney', 36], ['barney', 26], ['fred', 40], ['fred', 30]] + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ - function sortByOrder(collection, props, orders, guard) { + function sortByOrder(collection, iteratees, orders, guard) { if (collection == null) { return []; } - if (guard && isIterateeCall(props, orders, guard)) { + if (guard && isIterateeCall(iteratees, orders, guard)) { orders = null; } - if (!isArray(props)) { - props = props == null ? [] : [props]; + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; } if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } - return baseSortByOrder(collection, props, orders); + return baseSortByOrder(collection, iteratees, orders); } return sortByOrder; diff --git a/function/before.js b/function/before.js index 7678d251a..07e8f38b6 100644 --- a/function/before.js +++ b/function/before.js @@ -33,7 +33,8 @@ define([], function() { return function() { if (--n > 0) { result = func.apply(this, arguments); - } else { + } + if (n <= 1) { func = null; } return result; diff --git a/function/bind.js b/function/bind.js index 0fab79383..2c51bf006 100644 --- a/function/bind.js +++ b/function/bind.js @@ -12,7 +12,7 @@ define(['../internal/createWrapper', '../internal/replaceHolders', './restParam' * 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 does not set the "length" * property of bound functions. * * @static diff --git a/function/bindAll.js b/function/bindAll.js index 43a1a89bb..0900cafce 100644 --- a/function/bindAll.js +++ b/function/bindAll.js @@ -9,7 +9,7 @@ define(['../internal/baseFlatten', '../internal/createWrapper', '../object/funct * 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. + * **Note:** This method does not set the "length" property of bound functions. * * @static * @memberOf _ diff --git a/function/bindKey.js b/function/bindKey.js index d87912df7..71f309e68 100644 --- a/function/bindKey.js +++ b/function/bindKey.js @@ -11,7 +11,7 @@ define(['../internal/createWrapper', '../internal/replaceHolders', './restParam' * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. - * See [Peter Michaux's article](http://michaux.ca/articles/lazy-function-definition-pattern) + * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic diff --git a/function/curry.js b/function/curry.js index a74e28c8e..194d80b2d 100644 --- a/function/curry.js +++ b/function/curry.js @@ -13,7 +13,7 @@ define(['../internal/createCurry'], function(createCurry) { * 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 does not set the "length" property of curried functions. * * @static * @memberOf _ diff --git a/function/curryRight.js b/function/curryRight.js index 2cbc9c559..de46193cd 100644 --- a/function/curryRight.js +++ b/function/curryRight.js @@ -10,7 +10,7 @@ define(['../internal/createCurry'], function(createCurry) { * 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 does not set the "length" property of curried functions. * * @static * @memberOf _ diff --git a/function/once.js b/function/once.js index 5993ff479..e24008b50 100644 --- a/function/once.js +++ b/function/once.js @@ -18,7 +18,7 @@ define(['./before'], function(before) { * // `initialize` invokes `createApplication` once */ function once(func) { - return before(func, 2); + return before(2, func); } return once; diff --git a/function/partial.js b/function/partial.js index 96055c474..de58dbf1e 100644 --- a/function/partial.js +++ b/function/partial.js @@ -11,7 +11,7 @@ define(['../internal/createPartial'], function(createPartial) { * 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 does not set the "length" property of partially * applied functions. * * @static diff --git a/function/partialRight.js b/function/partialRight.js index a3ffeae4c..e6713e176 100644 --- a/function/partialRight.js +++ b/function/partialRight.js @@ -10,7 +10,7 @@ define(['../internal/createPartial'], function(createPartial) { * 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 does not set the "length" property of partially * applied functions. * * @static diff --git a/function/restParam.js b/function/restParam.js index 55b6b345b..76b67f2a5 100644 --- a/function/restParam.js +++ b/function/restParam.js @@ -1,5 +1,8 @@ define([], function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; @@ -32,7 +35,7 @@ define([], function() { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } - start = nativeMax(typeof start == 'undefined' ? (func.length - 1) : (+start || 0), 0); + start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, diff --git a/internal/assignDefaults.js b/internal/assignDefaults.js index 43f5add05..24a0503e2 100644 --- a/internal/assignDefaults.js +++ b/internal/assignDefaults.js @@ -1,5 +1,8 @@ define([], function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * Used by `_.defaults` to customize its `_.assign` use. * @@ -9,7 +12,7 @@ define([], function() { * @returns {*} Returns the value to assign to the destination object. */ function assignDefaults(objectValue, sourceValue) { - return typeof objectValue == 'undefined' ? sourceValue : objectValue; + return objectValue === undefined ? sourceValue : objectValue; } return assignDefaults; diff --git a/internal/assignOwnDefaults.js b/internal/assignOwnDefaults.js index 0bc598d39..2a6fe5681 100644 --- a/internal/assignOwnDefaults.js +++ b/internal/assignOwnDefaults.js @@ -1,5 +1,8 @@ define([], function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** Used for native method references. */ var objectProto = Object.prototype; @@ -9,7 +12,7 @@ define([], function() { /** * Used by `_.template` to customize its `_.assign` use. * - * **Note:** This method is like `assignDefaults` except that it ignores + * **Note:** This function is like `assignDefaults` except that it ignores * inherited property values when checking if a property is `undefined`. * * @private @@ -20,7 +23,7 @@ define([], function() { * @returns {*} Returns the value to assign to the destination object. */ function assignOwnDefaults(objectValue, sourceValue, key, object) { - return (typeof objectValue == 'undefined' || !hasOwnProperty.call(object, key)) + return (objectValue === undefined || !hasOwnProperty.call(object, key)) ? sourceValue : objectValue; } diff --git a/internal/assignWith.js b/internal/assignWith.js new file mode 100644 index 000000000..5fbe021d2 --- /dev/null +++ b/internal/assignWith.js @@ -0,0 +1,44 @@ +define(['./getSymbols', '../object/keys'], function(getSymbols, keys) { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used for native method references. */ + var arrayProto = Array.prototype; + + /** Native method references. */ + var push = arrayProto.push; + + /** + * A specialized version of `_.assign` for customizing assigned values without + * support for argument juggling, multiple sources, and `this` binding `customizer` + * functions. + * + * @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`. + */ + function assignWith(object, source, customizer) { + var props = keys(source); + push.apply(props, getSymbols(source)); + + var index = -1, + 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; + } + + return assignWith; +}); diff --git a/internal/baseAssign.js b/internal/baseAssign.js index 4d9878bcf..94814d90b 100644 --- a/internal/baseAssign.js +++ b/internal/baseAssign.js @@ -1,35 +1,38 @@ -define(['./baseCopy', '../object/keys'], function(baseCopy, keys) { +define(['./baseCopy', './getSymbols', '../lang/isNative', '../object/keys'], function(baseCopy, getSymbols, isNative, keys) { + + /** Native method references. */ + var preventExtensions = isNative(Object.preventExtensions = Object.preventExtensions) && preventExtensions; + + /** Used as `baseAssign`. */ + var nativeAssign = (function() { + // Avoid `Object.assign` in Firefox 34-37 which have an early implementation + // with a now defunct try/catch behavior. See https://bugzilla.mozilla.org/show_bug.cgi?id=1103344 + // for more details. + // + // Use `Object.preventExtensions` on a plain object instead of simply using + // `Object('x')` because Chrome and IE fail to throw an error when attempting + // to assign values to readonly indexes of strings in strict mode. + var object = { '1': 0 }, + func = preventExtensions && isNative(func = Object.assign) && func; + + try { func(preventExtensions(object), 'xo'); } catch(e) {} + return !object[1] && func; + }()); /** * The base implementation of `_.assign` without support for argument juggling, - * multiple sources, and `this` binding `customizer` functions. + * multiple sources, and `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. - * @param {Function} [customizer] The function to customize assigning values. - * @returns {Object} Returns the destination object. + * @returns {Object} Returns `object`. */ - function baseAssign(object, source, customizer) { - var props = keys(source); - if (!customizer) { - return baseCopy(source, object, props); - } - var index = -1, - 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)) || - (typeof value == 'undefined' && !(key in object))) { - object[key] = result; - } - } - return object; - } + var baseAssign = nativeAssign || function(object, source) { + return source == null + ? object + : baseCopy(source, getSymbols(source), baseCopy(source, keys(source), object)); + }; return baseAssign; }); diff --git a/internal/baseAt.js b/internal/baseAt.js index ef7e94829..33f58c36d 100644 --- a/internal/baseAt.js +++ b/internal/baseAt.js @@ -4,12 +4,12 @@ define(['./isIndex', './isLength'], function(isIndex, isLength) { var undefined; /** - * The base implementation of `_.at` without support for strings and individual - * key arguments. + * The base implementation of `_.at` without support for string collections + * and individual key arguments. * * @private * @param {Array|Object} collection The collection to iterate over. - * @param {number[]|string[]} [props] The property names or indexes of elements to pick. + * @param {number[]|string[]} props The property names or indexes of elements to pick. * @returns {Array} Returns the new array of picked elements. */ function baseAt(collection, props) { @@ -22,7 +22,6 @@ define(['./isIndex', './isLength'], function(isIndex, isLength) { while(++index < propsLength) { var key = props[index]; if (isArr) { - key = parseFloat(key); result[index] = isIndex(key, length) ? collection[key] : undefined; } else { result[index] = collection[key]; diff --git a/internal/baseCallback.js b/internal/baseCallback.js index 588c7589a..64bb13cad 100644 --- a/internal/baseCallback.js +++ b/internal/baseCallback.js @@ -1,4 +1,7 @@ -define(['./baseMatches', './baseMatchesProperty', './baseProperty', './bindCallback', '../utility/identity'], function(baseMatches, baseMatchesProperty, baseProperty, bindCallback, identity) { +define(['./baseMatches', './baseMatchesProperty', './bindCallback', '../utility/identity', '../utility/property'], function(baseMatches, baseMatchesProperty, bindCallback, identity, property) { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; /** * The base implementation of `_.callback` which supports specifying the @@ -13,7 +16,7 @@ define(['./baseMatches', './baseMatchesProperty', './baseProperty', './bindCallb function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { - return typeof thisArg == 'undefined' + return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } @@ -23,9 +26,9 @@ define(['./baseMatches', './baseMatchesProperty', './baseProperty', './bindCallb if (type == 'object') { return baseMatches(func); } - return typeof thisArg == 'undefined' - ? baseProperty(func + '') - : baseMatchesProperty(func + '', thisArg); + return thisArg === undefined + ? property(func) + : baseMatchesProperty(func, thisArg); } return baseCallback; diff --git a/internal/baseClone.js b/internal/baseClone.js index 5b614d548..00fa9a019 100644 --- a/internal/baseClone.js +++ b/internal/baseClone.js @@ -1,4 +1,7 @@ -define(['./arrayCopy', './arrayEach', './baseCopy', './baseForOwn', './initCloneArray', './initCloneByTag', './initCloneObject', '../lang/isArray', '../lang/isObject', '../object/keys'], function(arrayCopy, arrayEach, baseCopy, baseForOwn, initCloneArray, initCloneByTag, initCloneObject, isArray, isObject, keys) { +define(['./arrayCopy', './arrayEach', './baseAssign', './baseForOwn', './initCloneArray', './initCloneByTag', './initCloneObject', '../lang/isArray', '../lang/isObject'], function(arrayCopy, arrayEach, baseAssign, baseForOwn, initCloneArray, initCloneByTag, initCloneObject, isArray, isObject) { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', @@ -69,7 +72,7 @@ define(['./arrayCopy', './arrayEach', './baseCopy', './baseForOwn', './initClone if (customizer) { result = object ? customizer(value, key, object) : customizer(value); } - if (typeof result != 'undefined') { + if (result !== undefined) { return result; } if (!isObject(value)) { @@ -88,7 +91,7 @@ define(['./arrayCopy', './arrayEach', './baseCopy', './baseForOwn', './initClone if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = initCloneObject(isFunc ? {} : value); if (!isDeep) { - return baseCopy(value, result, keys(value)); + return baseAssign(result, value); } } else { return cloneableTags[tag] diff --git a/internal/baseCompareAscending.js b/internal/baseCompareAscending.js index 4ea642277..c78745c17 100644 --- a/internal/baseCompareAscending.js +++ b/internal/baseCompareAscending.js @@ -1,5 +1,8 @@ define([], function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * The base implementation of `compareAscending` which compares values and * sorts them in ascending order without guaranteeing a stable sort. @@ -14,10 +17,10 @@ define([], function() { var valIsReflexive = value === value, othIsReflexive = other === other; - if (value > other || !valIsReflexive || (typeof value == 'undefined' && othIsReflexive)) { + if (value > other || !valIsReflexive || (value === undefined && othIsReflexive)) { return 1; } - if (value < other || !othIsReflexive || (typeof other == 'undefined' && valIsReflexive)) { + if (value < other || !othIsReflexive || (other === undefined && valIsReflexive)) { return -1; } } diff --git a/internal/baseCopy.js b/internal/baseCopy.js index 2087178f2..9411c9a58 100644 --- a/internal/baseCopy.js +++ b/internal/baseCopy.js @@ -1,19 +1,17 @@ define([], function() { /** - * Copies the properties of `source` to `object`. + * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. - * @param {Object} [object={}] The object to copy properties to. * @param {Array} props The property names to copy. + * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ - function baseCopy(source, object, props) { - if (!props) { - props = object; - object = {}; - } + function baseCopy(source, props, object) { + object || (object = {}); + var index = -1, length = props.length; diff --git a/internal/baseFill.js b/internal/baseFill.js index c4661ebb7..bca329124 100644 --- a/internal/baseFill.js +++ b/internal/baseFill.js @@ -1,5 +1,8 @@ define([], function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * The base implementation of `_.fill` without an iteratee call guard. * @@ -17,7 +20,7 @@ define([], function() { if (start < 0) { start = -start > length ? 0 : (length + start); } - end = (typeof end == 'undefined' || end > length) ? length : (+end || 0); + end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } diff --git a/internal/baseFor.js b/internal/baseFor.js index 88f12fdfd..f0a768635 100644 --- a/internal/baseFor.js +++ b/internal/baseFor.js @@ -3,7 +3,7 @@ define(['./createBaseFor'], function(createBaseFor) { /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for - * each property. Iterator functions may exit iteration early by explicitly + * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private diff --git a/internal/baseGet.js b/internal/baseGet.js new file mode 100644 index 000000000..589b137d5 --- /dev/null +++ b/internal/baseGet.js @@ -0,0 +1,33 @@ +define(['./toObject'], function(toObject) { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** + * The base implementation of `get` without support for string paths + * and 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. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path, pathKey) { + if (object == null) { + return; + } + if (pathKey !== undefined && pathKey in toObject(object)) { + path = [pathKey]; + } + var index = -1, + length = path.length; + + while (object != null && ++index < length) { + var result = object = object[path[index]]; + } + return result; + } + + return baseGet; +}); diff --git a/internal/baseIsEqualDeep.js b/internal/baseIsEqualDeep.js index 6a7dddce2..23ac53740 100644 --- a/internal/baseIsEqualDeep.js +++ b/internal/baseIsEqualDeep.js @@ -3,7 +3,6 @@ define(['./equalArrays', './equalByTag', './equalObjects', '../lang/isArray', '. /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', - funcTag = '[object Function]', objectTag = '[object Object]'; /** Used for native method references. */ @@ -55,27 +54,23 @@ define(['./equalArrays', './equalByTag', './equalObjects', '../lang/isArray', '. othIsArr = isTypedArray(other); } } - var objIsObj = (objTag == objectTag || (isLoose && objTag == funcTag)), - othIsObj = (othTag == objectTag || (isLoose && othTag == funcTag)), + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } - if (isLoose) { - if (!isSameTag && !(objIsObj && othIsObj)) { - return false; - } - } else { + if (!isLoose) { var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (valWrapped || othWrapped) { return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } - if (!isSameTag) { - return false; - } + } + if (!isSameTag) { + return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. diff --git a/internal/baseIsMatch.js b/internal/baseIsMatch.js index a73230b81..2093b8d58 100644 --- a/internal/baseIsMatch.js +++ b/internal/baseIsMatch.js @@ -35,10 +35,10 @@ define(['./baseIsEqual'], function(baseIsEqual) { srcValue = values[index]; if (noCustomizer && strictCompareFlags[index]) { - var result = typeof objValue != 'undefined' || (key in object); + var result = objValue !== undefined || (key in object); } else { result = customizer ? customizer(objValue, srcValue, key) : undefined; - if (typeof result == 'undefined') { + if (result === undefined) { result = baseIsEqual(srcValue, objValue, customizer, true); } } diff --git a/internal/baseMap.js b/internal/baseMap.js index 71ece467f..1d5a6a00d 100644 --- a/internal/baseMap.js +++ b/internal/baseMap.js @@ -1,4 +1,4 @@ -define(['./baseEach'], function(baseEach) { +define(['./baseEach', './getLength', './isLength'], function(baseEach, getLength, isLength) { /** * The base implementation of `_.map` without support for callback shorthands @@ -10,9 +10,12 @@ define(['./baseEach'], function(baseEach) { * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { - var result = []; + var index = -1, + length = getLength(collection), + result = isLength(length) ? Array(length) : []; + baseEach(collection, function(value, key, collection) { - result.push(iteratee(value, key, collection)); + result[++index] = iteratee(value, key, collection); }); return result; } diff --git a/internal/baseMatches.js b/internal/baseMatches.js index 257357230..fbde9aac8 100644 --- a/internal/baseMatches.js +++ b/internal/baseMatches.js @@ -1,5 +1,8 @@ define(['./baseIsMatch', '../utility/constant', './isStrictComparable', '../object/keys', './toObject'], function(baseIsMatch, constant, isStrictComparable, keys, toObject) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * The base implementation of `_.matches` which does not clone `source`. * @@ -20,8 +23,10 @@ define(['./baseIsMatch', '../utility/constant', './isStrictComparable', '../obje if (isStrictComparable(value)) { return function(object) { - return object != null && object[key] === value && - (typeof value != 'undefined' || (key in toObject(object))); + if (object == null) { + return false; + } + return object[key] === value && (value !== undefined || (key in toObject(object))); }; } } diff --git a/internal/baseMatchesProperty.js b/internal/baseMatchesProperty.js index 930f56477..16bbc457c 100644 --- a/internal/baseMatchesProperty.js +++ b/internal/baseMatchesProperty.js @@ -1,23 +1,40 @@ -define(['./baseIsEqual', './isStrictComparable', './toObject'], function(baseIsEqual, isStrictComparable, toObject) { +define(['./baseGet', './baseIsEqual', './baseSlice', '../lang/isArray', './isKey', './isStrictComparable', '../array/last', './toObject', './toPath'], function(baseGet, baseIsEqual, baseSlice, isArray, isKey, isStrictComparable, last, toObject, toPath) { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; /** - * The base implementation of `_.matchesProperty` which does not coerce `key` - * to a string. + * The base implementation of `_.matchesProperty` which does not which does + * not clone `value`. * * @private - * @param {string} key The key of the property to get. + * @param {string} path The path of the property to get. * @param {*} value The value to compare. * @returns {Function} Returns the new function. */ - function baseMatchesProperty(key, value) { - if (isStrictComparable(value)) { - return function(object) { - return object != null && object[key] === value && - (typeof value != 'undefined' || (key in toObject(object))); - }; - } + function baseMatchesProperty(path, value) { + var isArr = isArray(path), + isCommon = isKey(path) && isStrictComparable(value), + pathKey = (path + ''); + + path = toPath(path); return function(object) { - return object != null && baseIsEqual(value, object[key], null, true); + 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] === value + ? (value !== undefined || (key in object)) + : baseIsEqual(value, object[key], null, true); }; } diff --git a/internal/baseMerge.js b/internal/baseMerge.js index 32aca8997..6b72ba847 100644 --- a/internal/baseMerge.js +++ b/internal/baseMerge.js @@ -1,8 +1,14 @@ -define(['./arrayEach', './baseForOwn', './baseMergeDeep', '../lang/isArray', './isLength', '../lang/isObject', './isObjectLike', '../lang/isTypedArray'], function(arrayEach, baseForOwn, baseMergeDeep, isArray, isLength, isObject, isObjectLike, isTypedArray) { +define(['./arrayEach', './baseMergeDeep', './getSymbols', '../lang/isArray', './isLength', '../lang/isObject', './isObjectLike', '../lang/isTypedArray', '../object/keys'], function(arrayEach, baseMergeDeep, getSymbols, isArray, isLength, isObject, isObjectLike, isTypedArray, keys) { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; + /** Used for native method references. */ + var arrayProto = Array.prototype; + + /** Native method references. */ + var push = arrayProto.push; + /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. @@ -13,29 +19,39 @@ define(['./arrayEach', './baseForOwn', './baseMergeDeep', '../lang/isArray', './ * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. - * @returns {Object} Returns the destination object. + * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isLength(source.length) && (isArray(source) || isTypedArray(source)); - (isSrcArr ? arrayEach : baseForOwn)(source, function(srcValue, key, source) { + if (!isSrcArr) { + var props = keys(source); + push.apply(props, getSymbols(source)); + } + arrayEach(props || source, function(srcValue, key) { + if (props) { + key = srcValue; + srcValue = source[key]; + } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); - return baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); + baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } - var value = object[key], - result = customizer ? customizer(value, srcValue, key, object, source) : undefined, - isCommon = typeof result == 'undefined'; + else { + var value = object[key], + result = customizer ? customizer(value, srcValue, key, object, source) : undefined, + isCommon = result === undefined; - if (isCommon) { - result = srcValue; - } - if ((isSrcArr || typeof result != 'undefined') && - (isCommon || (result === result ? (result !== value) : (value === value)))) { - object[key] = result; + if (isCommon) { + result = srcValue; + } + if ((isSrcArr || result !== undefined) && + (isCommon || (result === result ? (result !== value) : (value === value)))) { + object[key] = result; + } } }); return object; diff --git a/internal/baseMergeDeep.js b/internal/baseMergeDeep.js index 787cfe343..9cb8faecb 100644 --- a/internal/baseMergeDeep.js +++ b/internal/baseMergeDeep.js @@ -1,4 +1,4 @@ -define(['./arrayCopy', '../lang/isArguments', '../lang/isArray', './isLength', '../lang/isPlainObject', '../lang/isTypedArray', '../lang/toPlainObject'], function(arrayCopy, isArguments, isArray, isLength, isPlainObject, isTypedArray, toPlainObject) { +define(['./arrayCopy', './getLength', '../lang/isArguments', '../lang/isArray', './isLength', '../lang/isPlainObject', '../lang/isTypedArray', '../lang/toPlainObject'], function(arrayCopy, getLength, isArguments, isArray, isLength, isPlainObject, isTypedArray, toPlainObject) { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; @@ -30,14 +30,14 @@ define(['./arrayCopy', '../lang/isArguments', '../lang/isArray', './isLength', ' } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, - isCommon = typeof result == 'undefined'; + isCommon = result === undefined; if (isCommon) { result = srcValue; if (isLength(srcValue.length) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value - : ((value && value.length) ? arrayCopy(value) : []); + : (getLength(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) diff --git a/internal/baseProperty.js b/internal/baseProperty.js index 76f73047f..fb25a3f96 100644 --- a/internal/baseProperty.js +++ b/internal/baseProperty.js @@ -4,7 +4,7 @@ define([], function() { var undefined; /** - * The base implementation of `_.property` which does not coerce `key` to a string. + * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. diff --git a/internal/basePropertyDeep.js b/internal/basePropertyDeep.js new file mode 100644 index 000000000..e3d3b383b --- /dev/null +++ b/internal/basePropertyDeep.js @@ -0,0 +1,19 @@ +define(['./baseGet', './toPath'], function(baseGet, toPath) { + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new function. + */ + function basePropertyDeep(path) { + var pathKey = (path + ''); + path = toPath(path); + return function(object) { + return baseGet(object, path, pathKey); + }; + } + + return basePropertyDeep; +}); diff --git a/internal/basePullAt.js b/internal/basePullAt.js new file mode 100644 index 000000000..464467098 --- /dev/null +++ b/internal/basePullAt.js @@ -0,0 +1,31 @@ +define(['./isIndex'], function(isIndex) { + + /** Used for native method references. */ + var arrayProto = Array.prototype; + + /** Native method references. */ + var splice = arrayProto.splice; + + /** + * The base implementation of `_.pullAt` without support for individual + * index arguments and capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = indexes.length; + while (length--) { + var index = parseFloat(indexes[length]); + if (index != previous && isIndex(index)) { + var previous = index; + splice.call(array, index, 1); + } + } + return array; + } + + return basePullAt; +}); diff --git a/internal/baseSlice.js b/internal/baseSlice.js index bac32236a..499082f3d 100644 --- a/internal/baseSlice.js +++ b/internal/baseSlice.js @@ -1,5 +1,8 @@ define([], function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * The base implementation of `_.slice` without an iteratee call guard. * @@ -17,7 +20,7 @@ define([], function() { if (start < 0) { start = -start > length ? 0 : (length + start); } - end = (typeof end == 'undefined' || end > length) ? length : (+end || 0); + end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } diff --git a/internal/baseSortByOrder.js b/internal/baseSortByOrder.js index 2b41bf142..a1b95333d 100644 --- a/internal/baseSortByOrder.js +++ b/internal/baseSortByOrder.js @@ -1,30 +1,22 @@ -define(['./baseEach', './baseSortBy', './compareMultiple', './isLength'], function(baseEach, baseSortBy, compareMultiple, isLength) { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; +define(['./arrayMap', './baseCallback', './baseMap', './baseSortBy', './compareMultiple'], function(arrayMap, baseCallback, baseMap, baseSortBy, compareMultiple) { /** * The base implementation of `_.sortByOrder` without param guards. * * @private * @param {Array|Object|string} collection The collection to iterate over. - * @param {string[]} props The property names to sort by. - * @param {boolean[]} orders The sort orders of `props`. + * @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. */ - function baseSortByOrder(collection, props, orders) { - var index = -1, - length = collection.length, - result = isLength(length) ? Array(length) : []; + function baseSortByOrder(collection, iteratees, orders) { + var index = -1; - baseEach(collection, function(value) { - var length = props.length, - criteria = Array(length); + iteratees = arrayMap(iteratees, function(iteratee) { return baseCallback(iteratee); }); - while (length--) { - criteria[length] = value == null ? undefined : value[props[length]]; - } - result[++index] = { 'criteria': criteria, 'index': index, 'value': value }; + var result = baseMap(collection, function(value) { + var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { diff --git a/internal/baseValues.js b/internal/baseValues.js index f895af17f..bc8dff1fb 100644 --- a/internal/baseValues.js +++ b/internal/baseValues.js @@ -3,7 +3,7 @@ define([], function() { /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names - * returned by `keysFunc`. + * of `props`. * * @private * @param {Object} object The object to query. diff --git a/internal/binaryIndexBy.js b/internal/binaryIndexBy.js index eaa40d253..4bc5d450d 100644 --- a/internal/binaryIndexBy.js +++ b/internal/binaryIndexBy.js @@ -1,5 +1,8 @@ define([], function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** Native method references. */ var floor = Math.floor; @@ -29,7 +32,7 @@ define([], function() { var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, - valIsUndef = typeof value == 'undefined'; + valIsUndef = value === undefined; while (low < high) { var mid = floor((low + high) / 2), @@ -39,7 +42,7 @@ define([], function() { if (valIsNaN) { var setLow = isReflexive || retHighest; } else if (valIsUndef) { - setLow = isReflexive && (retHighest || typeof computed != 'undefined'); + setLow = isReflexive && (retHighest || computed !== undefined); } else { setLow = retHighest ? (computed <= value) : (computed < value); } diff --git a/internal/bindCallback.js b/internal/bindCallback.js index 46822a113..70210a3ae 100644 --- a/internal/bindCallback.js +++ b/internal/bindCallback.js @@ -1,5 +1,8 @@ define(['../utility/identity'], function(identity) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. @@ -14,7 +17,7 @@ define(['../utility/identity'], function(identity) { if (typeof func != 'function') { return identity; } - if (typeof thisArg == 'undefined') { + if (thisArg === undefined) { return func; } switch (argCount) { diff --git a/internal/compareMultiple.js b/internal/compareMultiple.js index 36cd596f5..bd4dd5d23 100644 --- a/internal/compareMultiple.js +++ b/internal/compareMultiple.js @@ -4,7 +4,7 @@ define(['./baseCompareAscending'], function(baseCompareAscending) { * Used by `_.sortByOrder` to compare multiple properties of each element * in a collection and stable sort them in the following order: * - * If orders is unspecified, sort in ascending order for all properties. + * If `orders` is unspecified, sort in ascending order for all properties. * Otherwise, for each property, sort in ascending order if its corresponding value in * orders is true, and descending order if false. * diff --git a/internal/createAssigner.js b/internal/createAssigner.js index af13ef72e..a0cb7fd15 100644 --- a/internal/createAssigner.js +++ b/internal/createAssigner.js @@ -1,4 +1,4 @@ -define(['./bindCallback', './isIterateeCall'], function(bindCallback, isIterateeCall) { +define(['./bindCallback', './isIterateeCall', '../function/restParam'], function(bindCallback, isIterateeCall, restParam) { /** * Creates a function that assigns properties of source object(s) to a given @@ -11,38 +11,32 @@ define(['./bindCallback', './isIterateeCall'], function(bindCallback, isIteratee * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { - return function() { - var args = arguments, - length = args.length, - object = args[0]; + return restParam(function(object, sources) { + var index = -1, + length = object == null ? 0 : sources.length, + customizer = length > 2 && sources[length - 2], + guard = length > 2 && sources[2], + thisArg = length > 1 && sources[length - 1]; - if (length < 2 || object == null) { - return object; - } - var customizer = args[length - 2], - thisArg = args[length - 1], - guard = args[3]; - - if (length > 3 && typeof customizer == 'function') { + if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { - customizer = (length > 2 && typeof thisArg == 'function') ? thisArg : null; + customizer = typeof thisArg == 'function' ? thisArg : null; length -= (customizer ? 1 : 0); } - if (guard && isIterateeCall(args[1], args[2], guard)) { - customizer = length == 3 ? null : customizer; - length = 2; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? null : customizer; + length = 1; } - var index = 0; while (++index < length) { - var source = args[index]; + var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; - }; + }); } return createAssigner; diff --git a/internal/createBaseEach.js b/internal/createBaseEach.js index 90088e0b8..4a93c585c 100644 --- a/internal/createBaseEach.js +++ b/internal/createBaseEach.js @@ -1,4 +1,4 @@ -define(['./isLength', './toObject'], function(isLength, toObject) { +define(['./getLength', './isLength', './toObject'], function(getLength, isLength, toObject) { /** * Creates a `baseEach` or `baseEachRight` function. @@ -10,7 +10,7 @@ define(['./isLength', './toObject'], function(isLength, toObject) { */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } diff --git a/internal/createForEach.js b/internal/createForEach.js index 858c202f9..fe72e18ba 100644 --- a/internal/createForEach.js +++ b/internal/createForEach.js @@ -1,5 +1,8 @@ define(['./bindCallback', '../lang/isArray'], function(bindCallback, isArray) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * Creates a function for `_.forEach` or `_.forEachRight`. * @@ -10,7 +13,7 @@ define(['./bindCallback', '../lang/isArray'], function(bindCallback, isArray) { */ function createForEach(arrayFunc, eachFunc) { return function(collection, iteratee, thisArg) { - return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection)) + return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee) : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); }; diff --git a/internal/createForIn.js b/internal/createForIn.js index 13e95471f..b39bb5e7f 100644 --- a/internal/createForIn.js +++ b/internal/createForIn.js @@ -1,5 +1,8 @@ define(['./bindCallback', '../object/keysIn'], function(bindCallback, keysIn) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * Creates a function for `_.forIn` or `_.forInRight`. * @@ -9,7 +12,7 @@ define(['./bindCallback', '../object/keysIn'], function(bindCallback, keysIn) { */ function createForIn(objectFunc) { return function(object, iteratee, thisArg) { - if (typeof iteratee != 'function' || typeof thisArg != 'undefined') { + if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee, keysIn); diff --git a/internal/createForOwn.js b/internal/createForOwn.js index edbe3c9c4..97bd3e853 100644 --- a/internal/createForOwn.js +++ b/internal/createForOwn.js @@ -1,5 +1,8 @@ define(['./bindCallback'], function(bindCallback) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * Creates a function for `_.forOwn` or `_.forOwnRight`. * @@ -9,7 +12,7 @@ define(['./bindCallback'], function(bindCallback) { */ function createForOwn(objectFunc) { return function(object, iteratee, thisArg) { - if (typeof iteratee != 'function' || typeof thisArg != 'undefined') { + if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee); diff --git a/internal/createReduce.js b/internal/createReduce.js index 8dfab7024..8576c299d 100644 --- a/internal/createReduce.js +++ b/internal/createReduce.js @@ -1,5 +1,8 @@ define(['./baseCallback', './baseReduce', '../lang/isArray'], function(baseCallback, baseReduce, isArray) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * Creates a function for `_.reduce` or `_.reduceRight`. * @@ -11,7 +14,7 @@ define(['./baseCallback', './baseReduce', '../lang/isArray'], function(baseCallb function createReduce(arrayFunc, eachFunc) { return function(collection, iteratee, accumulator, thisArg) { var initFromArray = arguments.length < 3; - return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection)) + return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee, accumulator, initFromArray) : baseReduce(collection, baseCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc); }; diff --git a/internal/equalArrays.js b/internal/equalArrays.js index b963da61e..c6e38c57c 100644 --- a/internal/equalArrays.js +++ b/internal/equalArrays.js @@ -37,7 +37,7 @@ define([], function() { ? customizer(othValue, arrValue, index) : customizer(arrValue, othValue, index); } - if (typeof result == 'undefined') { + if (result === undefined) { // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { var othIndex = othLength; diff --git a/internal/equalObjects.js b/internal/equalObjects.js index 126dd4206..1ba272f22 100644 --- a/internal/equalObjects.js +++ b/internal/equalObjects.js @@ -49,7 +49,7 @@ define(['../object/keys'], function(keys) { ? customizer(othValue, objValue, key) : customizer(objValue, othValue, key); } - if (typeof result == 'undefined') { + if (result === undefined) { // Recursively compare objects (susceptible to call stack limits). result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB); } diff --git a/internal/getLength.js b/internal/getLength.js new file mode 100644 index 000000000..e9b12ec71 --- /dev/null +++ b/internal/getLength.js @@ -0,0 +1,16 @@ +define(['./baseProperty'], function(baseProperty) { + + /** + * Gets the "length" property value of `object`. + * + * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) + * in Safari on iOS 8.1 ARM64. + * + * @private + * @param {Object} object The object to query. + * @returns {*} Returns the "length" value. + */ + var getLength = baseProperty('length'); + + return getLength; +}); diff --git a/internal/getSymbols.js b/internal/getSymbols.js new file mode 100644 index 000000000..c85234718 --- /dev/null +++ b/internal/getSymbols.js @@ -0,0 +1,18 @@ +define(['../utility/constant', '../lang/isNative', './toObject'], function(constant, isNative, toObject) { + + /** Native method references. */ + var getOwnPropertySymbols = isNative(getOwnPropertySymbols = Object.getOwnPropertySymbols) && getOwnPropertySymbols; + + /** + * Creates an array of the own symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !getOwnPropertySymbols ? constant([]) : function(object) { + return getOwnPropertySymbols(toObject(object)); + }; + + return getSymbols; +}); diff --git a/internal/initCloneByTag.js b/internal/initCloneByTag.js index 6c104e991..67d95409e 100644 --- a/internal/initCloneByTag.js +++ b/internal/initCloneByTag.js @@ -27,7 +27,6 @@ define(['./bufferClone'], function(bufferClone) { * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * - * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. diff --git a/internal/invokePath.js b/internal/invokePath.js new file mode 100644 index 000000000..f89e5a7ce --- /dev/null +++ b/internal/invokePath.js @@ -0,0 +1,26 @@ +define(['./baseGet', './baseSlice', './isKey', '../array/last', './toPath'], function(baseGet, baseSlice, isKey, last, toPath) { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** + * Invokes the method at `path` on `object`. + * + * @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 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); + } + var func = object == null ? object : object[path]; + return func == null ? undefined : func.apply(object, args); + } + + return invokePath; +}); diff --git a/internal/isIterateeCall.js b/internal/isIterateeCall.js index 7b64ccf52..e93d3d621 100644 --- a/internal/isIterateeCall.js +++ b/internal/isIterateeCall.js @@ -1,4 +1,4 @@ -define(['./isIndex', './isLength', '../lang/isObject'], function(isIndex, isLength, isObject) { +define(['./getLength', './isIndex', './isLength', '../lang/isObject'], function(getLength, isIndex, isLength, isObject) { /** * Checks if the provided arguments are from an iteratee call. @@ -15,7 +15,7 @@ define(['./isIndex', './isLength', '../lang/isObject'], function(isIndex, isLeng } var type = typeof index; if (type == 'number') { - var length = object.length, + var length = getLength(object), prereq = isLength(length) && isIndex(index, length); } else { prereq = type == 'string' && index in object; diff --git a/internal/isKey.js b/internal/isKey.js new file mode 100644 index 000000000..03d92e10d --- /dev/null +++ b/internal/isKey.js @@ -0,0 +1,28 @@ +define(['../lang/isArray', './toObject'], function(isArray, toObject) { + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]+|(["'])(?:(?!\1)[^\n\\]|\\.)*?)\1\]/, + reIsPlainProp = /^\w*$/; + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @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') { + return true; + } + if (isArray(value)) { + return false; + } + var result = !reIsDeepProp.test(value); + return result || (object != null && value in toObject(object)); + } + + return isKey; +}); diff --git a/internal/mapSet.js b/internal/mapSet.js index 444b9a852..7c1ec34b9 100644 --- a/internal/mapSet.js +++ b/internal/mapSet.js @@ -1,7 +1,7 @@ define([], function() { /** - * Adds `value` to `key` of the cache. + * Sets `value` to `key` of the cache. * * @private * @name set diff --git a/internal/pickByArray.js b/internal/pickByArray.js index 0ce305748..726cfcc96 100644 --- a/internal/pickByArray.js +++ b/internal/pickByArray.js @@ -2,7 +2,7 @@ define(['./toObject'], function(toObject) { /** * A specialized version of `_.pick` that picks `object` properties specified - * by the `props` array. + * by `props`. * * @private * @param {Object} object The source object. diff --git a/internal/root.js b/internal/root.js index 1bd60eb94..7f2ef4908 100644 --- a/internal/root.js +++ b/internal/root.js @@ -13,7 +13,7 @@ define([], function() { var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect free variable `global` from Node.js. */ - var freeGlobal = freeExports && freeModule && typeof global == 'object' && global; + var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; /** Detect free variable `self`. */ var freeSelf = objectTypes[typeof self] && self && self.Object && self; diff --git a/internal/shimIsPlainObject.js b/internal/shimIsPlainObject.js index 083b1b115..21901b116 100644 --- a/internal/shimIsPlainObject.js +++ b/internal/shimIsPlainObject.js @@ -1,5 +1,8 @@ define(['./baseForIn', './isObjectLike'], function(baseForIn, isObjectLike) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** `Object#toString` result references. */ var objectTag = '[object Object]'; @@ -43,7 +46,7 @@ define(['./baseForIn', './isObjectLike'], function(baseForIn, isObjectLike) { baseForIn(value, function(subValue, key) { result = key; }); - return typeof result == 'undefined' || hasOwnProperty.call(value, result); + return result === undefined || hasOwnProperty.call(value, result); } return shimIsPlainObject; diff --git a/internal/shimKeys.js b/internal/shimKeys.js index 8842d8b73..030c27982 100644 --- a/internal/shimKeys.js +++ b/internal/shimKeys.js @@ -11,7 +11,7 @@ define(['../lang/isArguments', '../lang/isArray', './isIndex', './isLength', '.. * own enumerable property names of `object`. * * @private - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { diff --git a/internal/toIterable.js b/internal/toIterable.js index 915412822..7e9f306b9 100644 --- a/internal/toIterable.js +++ b/internal/toIterable.js @@ -1,4 +1,4 @@ -define(['./isLength', '../lang/isObject', '../object/values'], function(isLength, isObject, values) { +define(['./getLength', './isLength', '../lang/isObject', '../object/values'], function(getLength, isLength, isObject, values) { /** * Converts `value` to an array-like object if it is not one. @@ -11,7 +11,7 @@ define(['./isLength', '../lang/isObject', '../object/values'], function(isLength if (value == null) { return []; } - if (!isLength(value.length)) { + if (!isLength(getLength(value))) { return values(value); } return isObject(value) ? value : Object(value); diff --git a/internal/toPath.js b/internal/toPath.js new file mode 100644 index 000000000..624c8f4c9 --- /dev/null +++ b/internal/toPath.js @@ -0,0 +1,28 @@ +define(['./baseToString', '../lang/isArray'], function(baseToString, isArray) { + + /** Used to match property names within property paths. */ + var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Converts `value` to property path array if it is not one. + * + * @private + * @param {*} value The value to process. + * @returns {Array} Returns the property path array. + */ + function toPath(value) { + if (isArray(value)) { + return value; + } + var result = []; + baseToString(value).replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + } + + return toPath; +}); diff --git a/lang/isEmpty.js b/lang/isEmpty.js index f7501e38b..42db6b956 100644 --- a/lang/isEmpty.js +++ b/lang/isEmpty.js @@ -1,4 +1,4 @@ -define(['./isArguments', './isArray', './isFunction', '../internal/isLength', '../internal/isObjectLike', './isString', '../object/keys'], function(isArguments, isArray, isFunction, isLength, isObjectLike, isString, keys) { +define(['../internal/getLength', './isArguments', './isArray', './isFunction', '../internal/isLength', '../internal/isObjectLike', './isString', '../object/keys'], function(getLength, isArguments, isArray, isFunction, isLength, isObjectLike, isString, keys) { /** * Checks if `value` is empty. A value is considered empty unless it is an @@ -31,7 +31,7 @@ define(['./isArguments', './isArray', './isFunction', '../internal/isLength', '. if (value == null) { return true; } - var length = value.length; + var length = getLength(value); if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) || (isObjectLike(value) && isFunction(value.splice)))) { return !length; diff --git a/lang/isEqual.js b/lang/isEqual.js index 583feb42a..581773f31 100644 --- a/lang/isEqual.js +++ b/lang/isEqual.js @@ -21,7 +21,7 @@ define(['../internal/baseIsEqual', '../internal/bindCallback', '../internal/isSt * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparing values. + * @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 @@ -52,7 +52,7 @@ define(['../internal/baseIsEqual', '../internal/bindCallback', '../internal/isSt return value === other; } var result = customizer ? customizer(value, other) : undefined; - return typeof result == 'undefined' ? baseIsEqual(value, other, customizer) : !!result; + return result === undefined ? baseIsEqual(value, other, customizer) : !!result; } return isEqual; diff --git a/lang/isMatch.js b/lang/isMatch.js index a22bcefe5..27e786035 100644 --- a/lang/isMatch.js +++ b/lang/isMatch.js @@ -1,5 +1,8 @@ define(['../internal/baseIsMatch', '../internal/bindCallback', '../internal/isStrictComparable', '../object/keys', '../internal/toObject'], function(baseIsMatch, bindCallback, isStrictComparable, keys, toObject) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * Performs a deep comparison between `object` and `source` to determine if * `object` contains equivalent property values. If `customizer` is provided @@ -17,7 +20,7 @@ define(['../internal/baseIsMatch', '../internal/bindCallback', '../internal/isSt * @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 comparing values. + * @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 @@ -50,12 +53,13 @@ define(['../internal/baseIsMatch', '../internal/bindCallback', '../internal/isSt return false; } customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3); + object = toObject(object); if (!customizer && length == 1) { var key = props[0], value = source[key]; if (isStrictComparable(value)) { - return value === object[key] && (typeof value != 'undefined' || (key in toObject(object))); + return value === object[key] && (value !== undefined || (key in object)); } } var values = Array(length), @@ -65,7 +69,7 @@ define(['../internal/baseIsMatch', '../internal/bindCallback', '../internal/isSt value = values[length] = source[props[length]]; strictCompareFlags[length] = isStrictComparable(value); } - return baseIsMatch(toObject(object), props, values, strictCompareFlags, customizer); + return baseIsMatch(object, props, values, strictCompareFlags, customizer); } return isMatch; diff --git a/lang/isNative.js b/lang/isNative.js index 4a25d69cc..bf3c10a20 100644 --- a/lang/isNative.js +++ b/lang/isNative.js @@ -4,7 +4,7 @@ define(['../string/escapeRegExp', '../internal/isObjectLike'], function(escapeRe var funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ - var reHostCtor = /^\[object .+?Constructor\]$/; + var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; @@ -19,7 +19,7 @@ define(['../string/escapeRegExp', '../internal/isObjectLike'], function(escapeRe var objToString = objectProto.toString; /** Used to detect if a method is native. */ - var reNative = RegExp('^' + + var reIsNative = RegExp('^' + escapeRegExp(objToString) .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); @@ -45,9 +45,9 @@ define(['../string/escapeRegExp', '../internal/isObjectLike'], function(escapeRe return false; } if (objToString.call(value) == funcTag) { - return reNative.test(fnToString.call(value)); + return reIsNative.test(fnToString.call(value)); } - return isObjectLike(value) && reHostCtor.test(value); + return isObjectLike(value) && reIsHostCtor.test(value); } return isNative; diff --git a/lang/isUndefined.js b/lang/isUndefined.js index 9b2c27439..3ff95bcfd 100644 --- a/lang/isUndefined.js +++ b/lang/isUndefined.js @@ -1,5 +1,8 @@ define([], function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** * Checks if `value` is `undefined`. * @@ -17,7 +20,7 @@ define([], function() { * // => false */ function isUndefined(value) { - return typeof value == 'undefined'; + return value === undefined; } return isUndefined; diff --git a/lang/toArray.js b/lang/toArray.js index 7df6fa480..ea89fce86 100644 --- a/lang/toArray.js +++ b/lang/toArray.js @@ -1,4 +1,4 @@ -define(['../internal/arrayCopy', '../internal/isLength', '../object/values'], function(arrayCopy, isLength, values) { +define(['../internal/arrayCopy', '../internal/getLength', '../internal/isLength', '../object/values'], function(arrayCopy, getLength, isLength, values) { /** * Converts `value` to an array. @@ -16,7 +16,7 @@ define(['../internal/arrayCopy', '../internal/isLength', '../object/values'], fu * // => [2, 3] */ function toArray(value) { - var length = value ? value.length : 0; + var length = value ? getLength(value) : 0; if (!isLength(length)) { return values(value); } diff --git a/main.js b/main.js index 200685115..cedaa4313 100644 --- a/main.js +++ b/main.js @@ -1,9 +1,9 @@ /** * @license - * lodash 3.6.0 (Custom Build) + * lodash 3.7.0 (Custom Build) * Build: `lodash modern exports="amd" -d -o ./main.js` * Copyright 2012-2015 The Dojo Foundation - * Based on Underscore.js 1.8.2 + * Based on Underscore.js 1.8.3 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ @@ -13,7 +13,7 @@ var undefined; /** Used as the semantic version number. */ - var VERSION = '3.6.0'; + var VERSION = '3.7.0'; /** Used to compose bitmasks for wrapper metadata. */ var BIND_FLAG = 1, @@ -87,30 +87,10 @@ reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - */ - var reComboMarks = /[\u0300-\u036f\ufe20-\ufe23]/g; - - /** - * Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect hexadecimal string values. */ - var reHexPrefix = /^0[xX]/; - - /** Used to detect host constructors (Safari > 5). */ - var reHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ - var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; - - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]+|(["'])(?:(?!\1)[^\n\\]|\\.)*?)\1\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). @@ -120,6 +100,30 @@ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.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 backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect hexadecimal string values. */ + var reHasHexPrefix = /^0[xX]/; + + /** Used to detect host constructors (Safari > 5). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ + var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; @@ -257,7 +261,7 @@ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect free variable `global` from Node.js. */ - var freeGlobal = freeExports && freeModule && typeof global == 'object' && global; + var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; /** Detect free variable `self`. */ var freeSelf = objectTypes[typeof self] && self && self.Object && self; @@ -289,10 +293,10 @@ var valIsReflexive = value === value, othIsReflexive = other === other; - if (value > other || !valIsReflexive || (typeof value == 'undefined' && othIsReflexive)) { + if (value > other || !valIsReflexive || (value === undefined && othIsReflexive)) { return 1; } - if (value < other || !othIsReflexive || (typeof other == 'undefined' && valIsReflexive)) { + if (value < other || !othIsReflexive || (other === undefined && valIsReflexive)) { return -1; } } @@ -435,7 +439,7 @@ * Used by `_.sortByOrder` to compare multiple properties of each element * in a collection and stable sort them in the following order: * - * If orders is unspecified, sort in ascending order for all properties. + * If `orders` is unspecified, sort in ascending order for all properties. * Otherwise, for each property, sort in ascending order if its corresponding value in * orders is true, and descending order if false. * @@ -712,9 +716,6 @@ /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; - /** Used to the length of n-tuples for `_.unzip`. */ - var getLength = baseProperty('length'); - /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; @@ -731,7 +732,7 @@ var oldDash = context._; /** Used to detect if a method is native. */ - var reNative = RegExp('^' + + var reIsNative = RegExp('^' + escapeRegExp(objToString) .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); @@ -742,8 +743,10 @@ ceil = Math.ceil, clearTimeout = context.clearTimeout, floor = Math.floor, + getOwnPropertySymbols = isNative(getOwnPropertySymbols = Object.getOwnPropertySymbols) && getOwnPropertySymbols, getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, push = arrayProto.push, + preventExtensions = isNative(Object.preventExtensions = Object.preventExtensions) && preventExtensions, propertyIsEnumerable = objectProto.propertyIsEnumerable, Set = isNative(Set = context.Set) && Set, setTimeout = context.setTimeout, @@ -763,6 +766,22 @@ return result; }()); + /** Used as `baseAssign`. */ + var nativeAssign = (function() { + // Avoid `Object.assign` in Firefox 34-37 which have an early implementation + // with a now defunct try/catch behavior. See https://bugzilla.mozilla.org/show_bug.cgi?id=1103344 + // for more details. + // + // Use `Object.preventExtensions` on a plain object instead of simply using + // `Object('x')` because Chrome and IE fail to throw an error when attempting + // to assign values to readonly indexes of strings in strict mode. + var object = { '1': 0 }, + func = preventExtensions && isNative(func = Object.assign) && func; + + try { func(preventExtensions(object), 'xo'); } catch(e) {} + return !object[1] && func; + }()); + /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, @@ -840,8 +859,8 @@ * `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`, * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`, * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`, - * `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, `merge`, - * `mixin`, `negate`, `noop`, `omit`, `once`, `pairs`, `partial`, `partialRight`, + * `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, + * `merge`, `mixin`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`, * `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `sortByOrder`, `splice`, @@ -855,15 +874,15 @@ * `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, * `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `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`, `max`, `min`, - * `noConflict`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, - * `random`, `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`, - * `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, - * `startCase`, `startsWith`, `sum`, `template`, `trim`, `trimLeft`, - * `trimRight`, `trunc`, `unescape`, `uniqueId`, `value`, and `words` + * `isBoolean`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, `isFinite` + * `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, + * `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, + * `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`, `noConflict`, + * `noop`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, + * `reduce`, `reduceRight`, `repeat`, `result`, `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. @@ -878,8 +897,8 @@ * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value - * wrapped.reduce(function(sum, n) { - * return sum + n; + * wrapped.reduce(function(total, n) { + * return total + n; * }); * // => 6 * @@ -939,6 +958,12 @@ var support = lodash.support = {}; (function(x) { + var Ctor = function() { this.x = x; }, + object = { '0': x, 'length': x }, + props = []; + + Ctor.prototype = { 'valueOf': x, 'y': x }; + for (var key in new Ctor) { props.push(key); } /** * Detect if functions can be decompiled by `Function#toString` @@ -976,8 +1001,8 @@ * In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object * indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat * `arguments` object indexes as non-enumerable and fail `hasOwnProperty` - * checks for indexes that exceed their function's formal parameters with - * associated values of `0`. + * checks for indexes that exceed the number of function parameters and + * whose associated argument values are `0`. * * @memberOf _.support * @type boolean @@ -987,7 +1012,7 @@ } catch(e) { support.nonEnumArgs = true; } - }(0, 0)); + }(1, 0)); /** * By default, the template delimiters used by lodash are like those in @@ -1234,7 +1259,7 @@ } /** - * Adds `value` to `key` of the cache. + * Sets `value` to `key` of the cache. * * @private * @name set @@ -1567,13 +1592,13 @@ * @returns {*} Returns the value to assign to the destination object. */ function assignDefaults(objectValue, sourceValue) { - return typeof objectValue == 'undefined' ? sourceValue : objectValue; + return objectValue === undefined ? sourceValue : objectValue; } /** * Used by `_.template` to customize its `_.assign` use. * - * **Note:** This method is like `assignDefaults` except that it ignores + * **Note:** This function is like `assignDefaults` except that it ignores * inherited property values when checking if a property is `undefined`. * * @private @@ -1584,26 +1609,26 @@ * @returns {*} Returns the value to assign to the destination object. */ function assignOwnDefaults(objectValue, sourceValue, key, object) { - return (typeof objectValue == 'undefined' || !hasOwnProperty.call(object, key)) + return (objectValue === undefined || !hasOwnProperty.call(object, key)) ? sourceValue : objectValue; } /** - * The base implementation of `_.assign` without support for argument juggling, - * multiple sources, and `this` binding `customizer` functions. + * A specialized version of `_.assign` for customizing assigned values without + * support for argument juggling, multiple sources, and `this` binding `customizer` + * functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. - * @param {Function} [customizer] The function to customize assigning values. - * @returns {Object} Returns the destination object. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. */ - function baseAssign(object, source, customizer) { + function assignWith(object, source, customizer) { var props = keys(source); - if (!customizer) { - return baseCopy(source, object, props); - } + push.apply(props, getSymbols(source)); + var index = -1, length = props.length; @@ -1613,7 +1638,7 @@ result = customizer(value, source[key], key, object, source); if ((result === result ? (result !== value) : (value === value)) || - (typeof value == 'undefined' && !(key in object))) { + (value === undefined && !(key in object))) { object[key] = result; } } @@ -1621,12 +1646,27 @@ } /** - * The base implementation of `_.at` without support for strings and individual - * key arguments. + * The base implementation of `_.assign` without support for argument juggling, + * multiple sources, and `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + var baseAssign = nativeAssign || function(object, source) { + return source == null + ? object + : baseCopy(source, getSymbols(source), baseCopy(source, keys(source), object)); + }; + + /** + * The base implementation of `_.at` without support for string collections + * and individual key arguments. * * @private * @param {Array|Object} collection The collection to iterate over. - * @param {number[]|string[]} [props] The property names or indexes of elements to pick. + * @param {number[]|string[]} props The property names or indexes of elements to pick. * @returns {Array} Returns the new array of picked elements. */ function baseAt(collection, props) { @@ -1639,7 +1679,6 @@ while(++index < propsLength) { var key = props[index]; if (isArr) { - key = parseFloat(key); result[index] = isIndex(key, length) ? collection[key] : undefined; } else { result[index] = collection[key]; @@ -1649,19 +1688,17 @@ } /** - * Copies the properties of `source` to `object`. + * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. - * @param {Object} [object={}] The object to copy properties to. * @param {Array} props The property names to copy. + * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ - function baseCopy(source, object, props) { - if (!props) { - props = object; - object = {}; - } + function baseCopy(source, props, object) { + object || (object = {}); + var index = -1, length = props.length; @@ -1685,7 +1722,7 @@ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { - return typeof thisArg == 'undefined' + return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } @@ -1695,9 +1732,9 @@ if (type == 'object') { return baseMatches(func); } - return typeof thisArg == 'undefined' - ? baseProperty(func + '') - : baseMatchesProperty(func + '', thisArg); + return thisArg === undefined + ? property(func) + : baseMatchesProperty(func, thisArg); } /** @@ -1719,7 +1756,7 @@ if (customizer) { result = object ? customizer(value, key, object) : customizer(value); } - if (typeof result != 'undefined') { + if (result !== undefined) { return result; } if (!isObject(value)) { @@ -1738,7 +1775,7 @@ if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = initCloneObject(isFunc ? {} : value); if (!isDeep) { - return baseCopy(value, result, keys(value)); + return baseAssign(result, value); } } else { return cloneableTags[tag] @@ -1909,7 +1946,7 @@ if (start < 0) { start = -start > length ? 0 : (length + start); } - end = (typeof end == 'undefined' || end > length) ? length : (+end || 0); + end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } @@ -2006,7 +2043,7 @@ /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for - * each property. Iterator functions may exit iteration early by explicitly + * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private @@ -2092,6 +2129,32 @@ return result; } + /** + * The base implementation of `get` without support for string paths + * and 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. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path, pathKey) { + if (object == null) { + return; + } + if (pathKey !== undefined && pathKey in toObject(object)) { + path = [pathKey]; + } + var index = -1, + length = path.length; + + while (object != null && ++index < length) { + var result = object = object[path[index]]; + } + return result; + } + /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. @@ -2160,27 +2223,23 @@ othIsArr = isTypedArray(other); } } - var objIsObj = (objTag == objectTag || (isLoose && objTag == funcTag)), - othIsObj = (othTag == objectTag || (isLoose && othTag == funcTag)), + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } - if (isLoose) { - if (!isSameTag && !(objIsObj && othIsObj)) { - return false; - } - } else { + if (!isLoose) { var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (valWrapped || othWrapped) { return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } - if (!isSameTag) { - return false; - } + } + if (!isSameTag) { + return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. @@ -2237,10 +2296,10 @@ srcValue = values[index]; if (noCustomizer && strictCompareFlags[index]) { - var result = typeof objValue != 'undefined' || (key in object); + var result = objValue !== undefined || (key in object); } else { result = customizer ? customizer(objValue, srcValue, key) : undefined; - if (typeof result == 'undefined') { + if (result === undefined) { result = baseIsEqual(srcValue, objValue, customizer, true); } } @@ -2261,9 +2320,12 @@ * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { - var result = []; + var index = -1, + length = getLength(collection), + result = isLength(length) ? Array(length) : []; + baseEach(collection, function(value, key, collection) { - result.push(iteratee(value, key, collection)); + result[++index] = iteratee(value, key, collection); }); return result; } @@ -2288,8 +2350,10 @@ if (isStrictComparable(value)) { return function(object) { - return object != null && object[key] === value && - (typeof value != 'undefined' || (key in toObject(object))); + if (object == null) { + return false; + } + return object[key] === value && (value !== undefined || (key in toObject(object))); }; } } @@ -2307,23 +2371,37 @@ } /** - * The base implementation of `_.matchesProperty` which does not coerce `key` - * to a string. + * The base implementation of `_.matchesProperty` which does not which does + * not clone `value`. * * @private - * @param {string} key The key of the property to get. + * @param {string} path The path of the property to get. * @param {*} value The value to compare. * @returns {Function} Returns the new function. */ - function baseMatchesProperty(key, value) { - if (isStrictComparable(value)) { - return function(object) { - return object != null && object[key] === value && - (typeof value != 'undefined' || (key in toObject(object))); - }; - } + function baseMatchesProperty(path, value) { + var isArr = isArray(path), + isCommon = isKey(path) && isStrictComparable(value), + pathKey = (path + ''); + + path = toPath(path); return function(object) { - return object != null && baseIsEqual(value, object[key], null, true); + 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] === value + ? (value !== undefined || (key in object)) + : baseIsEqual(value, object[key], null, true); }; } @@ -2337,29 +2415,39 @@ * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. - * @returns {Object} Returns the destination object. + * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isLength(source.length) && (isArray(source) || isTypedArray(source)); - (isSrcArr ? arrayEach : baseForOwn)(source, function(srcValue, key, source) { + if (!isSrcArr) { + var props = keys(source); + push.apply(props, getSymbols(source)); + } + arrayEach(props || source, function(srcValue, key) { + if (props) { + key = srcValue; + srcValue = source[key]; + } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); - return baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); + baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } - var value = object[key], - result = customizer ? customizer(value, srcValue, key, object, source) : undefined, - isCommon = typeof result == 'undefined'; + else { + var value = object[key], + result = customizer ? customizer(value, srcValue, key, object, source) : undefined, + isCommon = result === undefined; - if (isCommon) { - result = srcValue; - } - if ((isSrcArr || typeof result != 'undefined') && - (isCommon || (result === result ? (result !== value) : (value === value)))) { - object[key] = result; + if (isCommon) { + result = srcValue; + } + if ((isSrcArr || result !== undefined) && + (isCommon || (result === result ? (result !== value) : (value === value)))) { + object[key] = result; + } } }); return object; @@ -2392,14 +2480,14 @@ } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, - isCommon = typeof result == 'undefined'; + isCommon = result === undefined; if (isCommon) { result = srcValue; if (isLength(srcValue.length) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value - : ((value && value.length) ? arrayCopy(value) : []); + : (getLength(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) @@ -2424,7 +2512,7 @@ } /** - * The base implementation of `_.property` which does not coerce `key` to a string. + * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. @@ -2436,6 +2524,42 @@ }; } + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new function. + */ + function basePropertyDeep(path) { + var pathKey = (path + ''); + path = toPath(path); + return function(object) { + return baseGet(object, path, pathKey); + }; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * index arguments and capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = indexes.length; + while (length--) { + var index = parseFloat(indexes[length]); + if (index != previous && isIndex(index)) { + var previous = index; + splice.call(array, index, 1); + } + } + return array; + } + /** * The base implementation of `_.random` without support for argument juggling * and returning floating-point numbers. @@ -2502,7 +2626,7 @@ if (start < 0) { start = -start > length ? 0 : (length + start); } - end = (typeof end == 'undefined' || end > length) ? length : (+end || 0); + end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } @@ -2561,23 +2685,19 @@ * * @private * @param {Array|Object|string} collection The collection to iterate over. - * @param {string[]} props The property names to sort by. - * @param {boolean[]} orders The sort orders of `props`. + * @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. */ - function baseSortByOrder(collection, props, orders) { - var index = -1, - length = collection.length, - result = isLength(length) ? Array(length) : []; + function baseSortByOrder(collection, iteratees, orders) { + var callback = getCallback(), + index = -1; - baseEach(collection, function(value) { - var length = props.length, - criteria = Array(length); + iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); }); - while (length--) { - criteria[length] = value == null ? undefined : value[props[length]]; - } - result[++index] = { 'criteria': criteria, 'index': index, 'value': value }; + var result = baseMap(collection, function(value) { + var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { @@ -2657,7 +2777,7 @@ /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names - * returned by `keysFunc`. + * of `props`. * * @private * @param {Object} object The object to query. @@ -2774,7 +2894,7 @@ var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, - valIsUndef = typeof value == 'undefined'; + valIsUndef = value === undefined; while (low < high) { var mid = floor((low + high) / 2), @@ -2784,7 +2904,7 @@ if (valIsNaN) { var setLow = isReflexive || retHighest; } else if (valIsUndef) { - setLow = isReflexive && (retHighest || typeof computed != 'undefined'); + setLow = isReflexive && (retHighest || computed !== undefined); } else { setLow = retHighest ? (computed <= value) : (computed < value); } @@ -2811,7 +2931,7 @@ if (typeof func != 'function') { return identity; } - if (typeof thisArg == 'undefined') { + if (thisArg === undefined) { return func; } switch (argCount) { @@ -2971,38 +3091,32 @@ * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { - return function() { - var args = arguments, - length = args.length, - object = args[0]; + return restParam(function(object, sources) { + var index = -1, + length = object == null ? 0 : sources.length, + customizer = length > 2 && sources[length - 2], + guard = length > 2 && sources[2], + thisArg = length > 1 && sources[length - 1]; - if (length < 2 || object == null) { - return object; - } - var customizer = args[length - 2], - thisArg = args[length - 1], - guard = args[3]; - - if (length > 3 && typeof customizer == 'function') { + if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { - customizer = (length > 2 && typeof thisArg == 'function') ? thisArg : null; + customizer = typeof thisArg == 'function' ? thisArg : null; length -= (customizer ? 1 : 0); } - if (guard && isIterateeCall(args[1], args[2], guard)) { - customizer = length == 3 ? null : customizer; - length = 2; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? null : customizer; + length = 1; } - var index = 0; while (++index < length) { - var source = args[index]; + var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; - }; + }); } /** @@ -3015,7 +3129,7 @@ */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } @@ -3292,7 +3406,7 @@ */ function createForEach(arrayFunc, eachFunc) { return function(collection, iteratee, thisArg) { - return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection)) + return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee) : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); }; @@ -3307,7 +3421,7 @@ */ function createForIn(objectFunc) { return function(object, iteratee, thisArg) { - if (typeof iteratee != 'function' || typeof thisArg != 'undefined') { + if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee, keysIn); @@ -3323,7 +3437,7 @@ */ function createForOwn(objectFunc) { return function(object, iteratee, thisArg) { - if (typeof iteratee != 'function' || typeof thisArg != 'undefined') { + if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee); @@ -3370,7 +3484,7 @@ function createReduce(arrayFunc, eachFunc) { return function(collection, iteratee, accumulator, thisArg) { var initFromArray = arguments.length < 3; - return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection)) + return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee, accumulator, initFromArray) : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc); }; @@ -3639,7 +3753,7 @@ ? customizer(othValue, arrValue, index) : customizer(arrValue, othValue, index); } - if (typeof result == 'undefined') { + if (result === undefined) { // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { var othIndex = othLength; @@ -3738,7 +3852,7 @@ ? customizer(othValue, objValue, key) : customizer(objValue, othValue, key); } - if (typeof result == 'undefined') { + if (result === undefined) { // Recursively compare objects (susceptible to call stack limits). result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB); } @@ -3863,6 +3977,29 @@ return collection ? result(collection, target, fromIndex) : result; } + /** + * Gets the "length" property value of `object`. + * + * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) + * in Safari on iOS 8.1 ARM64. + * + * @private + * @param {Object} object The object to query. + * @returns {*} Returns the "length" value. + */ + var getLength = baseProperty('length'); + + /** + * Creates an array of the own symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !getOwnPropertySymbols ? constant([]) : function(object) { + return getOwnPropertySymbols(toObject(object)); + }; + /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * @@ -3931,7 +4068,6 @@ * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * - * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. @@ -3965,6 +4101,25 @@ return result; } + /** + * Invokes the method at `path` on `object`. + * + * @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 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); + } + var func = object == null ? object : object[path]; + return func == null ? undefined : func.apply(object, args); + } + /** * Checks if `value` is a valid array-like index. * @@ -3994,7 +4149,7 @@ } var type = typeof index; if (type == 'number') { - var length = object.length, + var length = getLength(object), prereq = isLength(length) && isIndex(index, length); } else { prereq = type == 'string' && index in object; @@ -4006,6 +4161,26 @@ return false; } + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @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') { + return true; + } + if (isArray(value)) { + return false; + } + var result = !reIsDeepProp.test(value); + return result || (object != null && value in toObject(object)); + } + /** * Checks if `func` has a lazy counterpart. * @@ -4115,7 +4290,7 @@ /** * A specialized version of `_.pick` that picks `object` properties specified - * by the `props` array. + * by `props`. * * @private * @param {Object} object The source object. @@ -4241,7 +4416,7 @@ baseForIn(value, function(subValue, key) { result = key; }); - return typeof result == 'undefined' || hasOwnProperty.call(value, result); + return result === undefined || hasOwnProperty.call(value, result); } /** @@ -4249,7 +4424,7 @@ * own enumerable property names of `object`. * * @private - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { @@ -4284,7 +4459,7 @@ if (value == null) { return []; } - if (!isLength(value.length)) { + if (!isLength(getLength(value))) { return values(value); } return isObject(value) ? value : Object(value); @@ -4301,6 +4476,24 @@ return isObject(value) ? value : Object(value); } + /** + * Converts `value` to property path array if it is not one. + * + * @private + * @param {*} value The value to process. + * @returns {Array} Returns the property path array. + */ + function toPath(value) { + if (isArray(value)) { + return value; + } + var result = []; + baseToString(value).replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + } + /** * Creates a clone of `wrapper`. * @@ -4885,7 +5078,8 @@ argsLength = arguments.length, caches = [], indexOf = getIndexOf(), - isCommon = indexOf == baseIndexOf; + isCommon = indexOf == baseIndexOf, + result = []; while (++argsIndex < argsLength) { var value = arguments[argsIndex]; @@ -4895,10 +5089,12 @@ } } argsLength = args.length; + if (argsLength < 2) { + return result; + } var array = args[0], index = -1, length = array ? array.length : 0, - result = [], seen = caches[0]; outer: @@ -5066,17 +5262,8 @@ array || (array = []); indexes = baseFlatten(indexes); - var length = indexes.length, - result = baseAt(array, indexes); - - indexes.sort(baseCompareAscending); - while (length--) { - var index = parseFloat(indexes[length]); - if (index != previous && isIndex(index)) { - var previous = index; - splice.call(array, index, 1); - } - } + var result = baseAt(array, indexes); + basePullAt(array, indexes.sort(baseCompareAscending)); return result; }); @@ -5120,19 +5307,23 @@ * // => [2, 4] */ function remove(array, predicate, thisArg) { + var result = []; + if (!(array && array.length)) { + return result; + } var index = -1, - length = array ? array.length : 0, - result = []; + indexes = [], + length = array.length; predicate = getCallback(predicate, thisArg, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); - splice.call(array, index--, 1); - length--; + indexes.push(index); } } + basePullAt(array, indexes); return result; } @@ -5157,7 +5348,7 @@ /** * Creates a slice of `array` from `start` up to, but not including, `end`. * - * **Note:** This function is used instead of `Array#slice` to support node + * **Note:** This method is used instead of `Array#slice` to support node * lists in IE < 9 and to ensure dense arrays are returned. * * @static @@ -5456,12 +5647,13 @@ }); /** - * Creates a duplicate-value-free version of an array using `SameValueZero` - * for equality comparisons. Providing `true` for `isSorted` performs a faster - * search algorithm for sorted arrays. If an iteratee function is provided it - * is invoked for each value 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). + * Creates a duplicate-free version of an array, using `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 is 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). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. @@ -5489,8 +5681,8 @@ * @returns {Array} Returns the new duplicate-value-free array. * @example * - * _.uniq([1, 2, 1]); - * // => [1, 2] + * _.uniq([2, 1, 2]); + * // => [2, 1] * * // using `isSorted` * _.uniq([1, 1, 2], true); @@ -5940,7 +6132,7 @@ * // => ['barney', 'pebbles'] */ var at = restParam(function(collection, props) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; if (isLength(length)) { collection = toIterable(collection); } @@ -6045,7 +6237,7 @@ if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } - if (typeof predicate != 'function' || typeof thisArg != 'undefined') { + if (typeof predicate != 'function' || thisArg !== undefined) { predicate = getCallback(predicate, thisArg, 3); } return func(collection, predicate); @@ -6215,10 +6407,10 @@ /** * 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). Iterator functions may exit iteration early + * (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 + * **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. * @@ -6348,7 +6540,7 @@ * // => true */ function includes(collection, target, fromIndex, guard) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; if (!isLength(length)) { collection = values(collection); length = collection.length; @@ -6417,16 +6609,16 @@ }); /** - * Invokes the method named by `methodName` on 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 is invoked for, and `this` bound to, each element in `collection`. + * Invokes the method at `path` on 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 is + * invoked for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|string} methodName The name of the method to invoke or + * @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. * @returns {Array} Returns the array of results. @@ -6438,15 +6630,16 @@ * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ - var invoke = restParam(function(collection, methodName, args) { + var invoke = restParam(function(collection, path, args) { var index = -1, - isFunc = typeof methodName == 'function', - length = collection ? collection.length : 0, + isFunc = typeof path == 'function', + isProp = isKey(path), + length = getLength(collection), result = isLength(length) ? Array(length) : []; baseEach(collection, function(value) { - var func = isFunc ? methodName : (value != null && value[methodName]); - result[++index] = func ? func.apply(value, args) : undefined; + var func = isFunc ? path : (isProp && value != null && value[path]); + result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); }); return result; }); @@ -6483,7 +6676,6 @@ * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. - * create a `_.property` or `_.matches` style callback respectively. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new mapped array. * @example @@ -6577,13 +6769,13 @@ }, function() { return [[], []]; }); /** - * Gets the value of `key` from all elements in `collection`. + * Gets the property value of `path` from all elements in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. - * @param {string} key The key of the property to pluck. + * @param {Array|string} path The path of the property to pluck. * @returns {Array} Returns the property values. * @example * @@ -6599,8 +6791,8 @@ * _.pluck(userIndex, 'age'); * // => [36, 40] (iteration order is not guaranteed) */ - function pluck(collection, key) { - return map(collection, baseProperty(key)); + function pluck(collection, path) { + return map(collection, property(path)); } /** @@ -6628,8 +6820,8 @@ * @returns {*} Returns the accumulated value. * @example * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; + * _.reduce([1, 2], function(total, n) { + * return total + n; * }); * // => 3 * @@ -6801,7 +6993,7 @@ * // => 7 */ function size(collection) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; return isLength(length) ? length : keys(collection).length; } @@ -6859,7 +7051,7 @@ if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } - if (typeof predicate != 'function' || typeof thisArg != 'undefined') { + if (typeof predicate != 'function' || thisArg !== undefined) { predicate = getCallback(predicate, thisArg, 3); } return func(collection, predicate); @@ -6887,9 +7079,8 @@ * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. - * @param {Array|Function|Object|string} [iteratee=_.identity] The function - * invoked per iteration. If a property name or an object is provided it is - * used to create a `_.property` or `_.matches` style callback respectively. + * @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 @@ -6918,104 +7109,112 @@ if (collection == null) { return []; } - var index = -1, - length = collection.length, - result = isLength(length) ? Array(length) : []; - if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } + var index = -1; iteratee = getCallback(iteratee, thisArg, 3); - baseEach(collection, function(value, key, collection) { - result[++index] = { 'criteria': iteratee(value, key, collection), 'index': index, 'value': value }; + + 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 sorts by property names - * instead of an iteratee function. + * 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 {...(string|string[])} props The property names to sort by, - * specified as individual property names or arrays of property names. + * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees + * The iteratees to sort by, specified as individual values or arrays of values. * @returns {Array} Returns the new sorted array. * @example * * var users = [ + * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 26 }, - * { 'user': 'fred', 'age': 30 } + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 34 } * ]; * * _.map(_.sortByAll(users, ['user', 'age']), _.values); - * // => [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] + * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] + * + * _.map(_.sortByAll(users, 'user', function(chr) { + * return Math.floor(chr.age / 10); + * }), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ - function sortByAll() { - var args = arguments, - collection = args[0], - guard = args[3], - index = 0, - length = args.length - 1; - + var sortByAll = restParam(function(collection, iteratees) { if (collection == null) { return []; } - var props = Array(length); - while (index < length) { - props[index] = args[++index]; + var guard = iteratees[2]; + if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { + iteratees.length = 1; } - if (guard && isIterateeCall(args[1], args[2], guard)) { - props = args[1]; - } - return baseSortByOrder(collection, baseFlatten(props), []); - } + return baseSortByOrder(collection, baseFlatten(iteratees), []); + }); /** * This method is like `_.sortByAll` except that it allows specifying the - * sort orders of the property names to sort by. A truthy value in `orders` - * will sort the corresponding property name in ascending order while a - * falsey value will sort it in descending order. + * sort orders of the iteratees to sort by. A truthy value in `orders` will + * sort the corresponding property name in ascending order while a falsey + * value will sort it in descending order. + * + * 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 {string[]} props The property names to sort by. - * @param {boolean[]} orders The sort orders of `props`. + * @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': 'barney', 'age': 26 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 30 } + * { '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'], [true, false]), _.values); - * // => [['barney', 36], ['barney', 26], ['fred', 40], ['fred', 30]] + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ - function sortByOrder(collection, props, orders, guard) { + function sortByOrder(collection, iteratees, orders, guard) { if (collection == null) { return []; } - if (guard && isIterateeCall(props, orders, guard)) { + if (guard && isIterateeCall(iteratees, orders, guard)) { orders = null; } - if (!isArray(props)) { - props = props == null ? [] : [props]; + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; } if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } - return baseSortByOrder(collection, props, orders); + return baseSortByOrder(collection, iteratees, orders); } /** @@ -7168,7 +7367,8 @@ return function() { if (--n > 0) { result = func.apply(this, arguments); - } else { + } + if (n <= 1) { func = null; } return result; @@ -7183,7 +7383,7 @@ * 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 does not set the "length" * property of bound functions. * * @static @@ -7225,7 +7425,7 @@ * 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. + * **Note:** This method does not set the "length" property of bound functions. * * @static * @memberOf _ @@ -7266,7 +7466,7 @@ * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. - * See [Peter Michaux's article](http://michaux.ca/articles/lazy-function-definition-pattern) + * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic @@ -7323,7 +7523,7 @@ * 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 does not set the "length" property of curried functions. * * @static * @memberOf _ @@ -7362,7 +7562,7 @@ * 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 does not set the "length" property of curried functions. * * @static * @memberOf _ @@ -7774,7 +7974,7 @@ * // `initialize` invokes `createApplication` once */ function once(func) { - return before(func, 2); + return before(2, func); } /** @@ -7785,7 +7985,7 @@ * 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 does not set the "length" property of partially * applied functions. * * @static @@ -7818,7 +8018,7 @@ * 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 does not set the "length" property of partially * applied functions. * * @static @@ -7902,7 +8102,7 @@ if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } - start = nativeMax(typeof start == 'undefined' ? (func.length - 1) : (+start || 0), 0); + start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, @@ -8306,7 +8506,7 @@ if (value == null) { return true; } - var length = value.length; + var length = getLength(value); if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) || (isObjectLike(value) && isFunction(value.splice)))) { return !length; @@ -8332,7 +8532,7 @@ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparing values. + * @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 @@ -8363,7 +8563,7 @@ return value === other; } var result = customizer ? customizer(value, other) : undefined; - return typeof result == 'undefined' ? baseIsEqual(value, other, customizer) : !!result; + return result === undefined ? baseIsEqual(value, other, customizer) : !!result; } /** @@ -8485,7 +8685,7 @@ * @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 comparing values. + * @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 @@ -8518,12 +8718,13 @@ return false; } customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3); + object = toObject(object); if (!customizer && length == 1) { var key = props[0], value = source[key]; if (isStrictComparable(value)) { - return value === object[key] && (typeof value != 'undefined' || (key in toObject(object))); + return value === object[key] && (value !== undefined || (key in object)); } } var values = Array(length), @@ -8533,7 +8734,7 @@ value = values[length] = source[props[length]]; strictCompareFlags[length] = isStrictComparable(value); } - return baseIsMatch(toObject(object), props, values, strictCompareFlags, customizer); + return baseIsMatch(object, props, values, strictCompareFlags, customizer); } /** @@ -8588,9 +8789,9 @@ return false; } if (objToString.call(value) == funcTag) { - return reNative.test(fnToString.call(value)); + return reIsNative.test(fnToString.call(value)); } - return isObjectLike(value) && reHostCtor.test(value); + return isObjectLike(value) && reIsHostCtor.test(value); } /** @@ -8758,7 +8959,7 @@ * // => false */ function isUndefined(value) { - return typeof value == 'undefined'; + return value === undefined; } /** @@ -8777,7 +8978,7 @@ * // => [2, 3] */ function toArray(value) { - var length = value ? value.length : 0; + var length = value ? getLength(value) : 0; if (!isLength(length)) { return values(value); } @@ -8823,13 +9024,17 @@ * The `customizer` is bound to `thisArg` and invoked with five arguments: * (objectValue, sourceValue, key, object, source). * + * **Note:** This method mutates `object` and is based on + * [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). + * + * * @static * @memberOf _ * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. - * @param {Function} [customizer] The function to customize assigning values. + * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example @@ -8839,13 +9044,17 @@ * * // using a customizer callback * var defaults = _.partialRight(_.assign, function(value, other) { - * return typeof value == 'undefined' ? other : value; + * return _.isUndefined(value) ? other : value; * }); * * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ - var assign = createAssigner(baseAssign); + var assign = createAssigner(function(object, source, customizer) { + return customizer + ? assignWith(object, source, customizer) + : baseAssign(object, source); + }); /** * Creates an object that inherits from the given `prototype` object. If a @@ -8886,7 +9095,7 @@ if (guard && isIterateeCall(prototype, properties, guard)) { properties = null; } - return properties ? baseCopy(properties, result, keys(properties)) : result; + return properties ? baseAssign(result, properties) : result; } /** @@ -8894,6 +9103,8 @@ * object for all destination properties that resolve to `undefined`. Once a * property is set, additional values of the same property are ignored. * + * **Note:** This method mutates `object`. + * * @static * @memberOf _ * @category Object @@ -9017,7 +9228,7 @@ /** * 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). Iterator functions may exit + * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static @@ -9073,7 +9284,7 @@ /** * 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). Iterator functions may exit iteration + * three arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static @@ -9146,24 +9357,68 @@ } /** - * Checks if `key` exists as a direct property of `object` instead of an - * inherited property. + * Gets the property value of `path` on `object`. If the resolved value is + * `undefined` the `defaultValue` is used in its place. * * @static * @memberOf _ * @category Object - * @param {Object} object The object to inspect. - * @param {string} key The key to check. - * @returns {boolean} Returns `true` if `key` is a direct property, else `false`. + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. + * @returns {*} Returns the resolved value. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 3 }; + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * - * _.has(object, 'b'); + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, toPath(path), path + ''); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property. + * + * @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`. + * @example + * + * var object = { 'a': { 'b': { 'c': 3 } } }; + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b.c'); + * // => true + * + * _.has(object, ['a', 'b', 'c']); * // => true */ - function has(object, key) { - return object ? hasOwnProperty.call(object, key) : 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)); + path = last(path); + result = object != null && hasOwnProperty.call(object, path); + } + return result; } /** @@ -9226,7 +9481,7 @@ * @static * @memberOf _ * @category Object - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * @@ -9249,7 +9504,7 @@ length = object.length; } if ((typeof Ctor == 'function' && Ctor.prototype === object) || - (typeof object != 'function' && (length && isLength(length)))) { + (typeof object != 'function' && isLength(length))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; @@ -9263,7 +9518,7 @@ * @static * @memberOf _ * @category Object - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * @@ -9371,7 +9626,7 @@ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. - * @param {Function} [customizer] The function to customize merging properties. + * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example @@ -9456,7 +9711,7 @@ * @static * @memberOf _ * @category Object - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * @@ -9512,41 +9767,93 @@ }); /** - * Resolves the value of property `key` on `object`. If the value of `key` is - * a function it is invoked with the `this` binding of `object` and its result - * is returned, else the property value is returned. If the property value is - * `undefined` the `defaultValue` is used in its place. + * This method is like `_.get` except that if the resolved value is a function + * it is invoked with the `this` binding of its parent object and its result + * is returned. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. - * @param {string} key The key of the property to resolve. - * @param {*} [defaultValue] The value returned if the property value - * resolves to `undefined`. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * - * var object = { 'user': 'fred', 'age': _.constant(40) }; + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * - * _.result(object, 'user'); - * // => 'fred' + * _.result(object, 'a[0].b.c1'); + * // => 3 * - * _.result(object, 'age'); - * // => 40 + * _.result(object, 'a[0].b.c2'); + * // => 4 * - * _.result(object, 'status', 'busy'); - * // => 'busy' + * _.result(object, 'a.b.c', 'default'); + * // => 'default' * - * _.result(object, 'status', _.constant('busy')); - * // => 'busy' + * _.result(object, 'a.b.c', _.constant('default')); + * // => 'default' */ - function result(object, key, defaultValue) { - var value = object == null ? undefined : object[key]; - if (typeof value == 'undefined') { - value = defaultValue; + function result(object, path, defaultValue) { + var 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; } - return isFunction(value) ? value.call(object) : value; + return isFunction(result) ? result.call(object) : result; + } + + /** + * Sets the property value of `path` on `object`. If a portion of `path` + * does not exist it is created. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to augment. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, 'x[0].y.z', 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + if (object == null) { + return object; + } + var pathKey = (path + ''); + path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path); + + var index = -1, + length = path.length, + endIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = path[index]; + if (isObject(nested)) { + if (index == endIndex) { + nested[key] = value; + } else if (nested[key] == null) { + nested[key] = isIndex(path[index + 1]) ? [] : {}; + } + } + nested = nested[key]; + } + return object; } /** @@ -9554,7 +9861,7 @@ * `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). Iterator functions + * with four arguments: (accumulator, value, key, object). Iteratee functions * may exit iteration early by explicitly returning `false`. * * @static @@ -9697,7 +10004,7 @@ } else { end = +end || 0; } - return value >= start && value < end; + return value >= nativeMin(start, end) && value < nativeMax(start, end); } /** @@ -9822,7 +10129,7 @@ */ function deburr(string) { string = baseToString(string); - return string && string.replace(reLatin1, deburrLetter).replace(reComboMarks, ''); + return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } /** @@ -9851,7 +10158,7 @@ target = (target + ''); var length = string.length; - position = typeof position == 'undefined' + position = position === undefined ? length : nativeMin(position < 0 ? 0 : (+position || 0), length); @@ -9873,9 +10180,10 @@ * (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 [#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. + * 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. * * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping) * to reduce XSS vectors. @@ -10069,7 +10377,7 @@ radix = +radix; } string = trim(string); - return nativeParseInt(string, radix || (reHexPrefix.test(string) ? 16 : 10)); + return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); }; } @@ -10294,9 +10602,9 @@ options = otherOptions = null; } string = baseToString(string); - options = baseAssign(baseAssign({}, otherOptions || options), settings, assignOwnDefaults); + options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults); - var imports = baseAssign(baseAssign({}, options.imports), settings.imports, assignOwnDefaults), + var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); @@ -10700,9 +11008,7 @@ if (guard && isIterateeCall(func, thisArg, guard)) { thisArg = null; } - return isObjectLike(func) - ? matches(func) - : baseCallback(func, thisArg); + return baseCallback(func, thisArg); } /** @@ -10776,7 +11082,7 @@ } /** - * Creates a function which compares the property value of `key` on a given + * Creates a function which compares the property value of `path` on a given * object to `value`. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, @@ -10786,7 +11092,7 @@ * @static * @memberOf _ * @category Utility - * @param {string} key The key of the property to get. + * @param {Array|string} path The path of the property to get. * @param {*} value The value to compare. * @returns {Function} Returns the new function. * @example @@ -10799,22 +11105,75 @@ * _.find(users, _.matchesProperty('user', 'fred')); * // => { 'user': 'fred' } */ - function matchesProperty(key, value) { - return baseMatchesProperty(key + '', baseClone(value, true)); + function matchesProperty(path, value) { + return baseMatchesProperty(path, baseClone(value, true)); } + /** + * Creates a function which invokes the method at `path` on a given object. + * + * @static + * @memberOf _ + * @category Utility + * @param {Array|string} path The path of the method to invoke. + * @returns {Function} Returns the new function. + * @example + * + * var objects = [ + * { 'a': { 'b': { 'c': _.constant(2) } } }, + * { 'a': { 'b': { 'c': _.constant(1) } } } + * ]; + * + * _.map(objects, _.method('a.b.c')); + * // => [2, 1] + * + * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c'); + * // => [1, 2] + */ + var method = restParam(function(path, args) { + return function(object) { + return invokePath(object, path, args); + } + }); + + /** + * The opposite of `_.method`; this method creates a function which invokes + * the method at a given path on `object`. + * + * @static + * @memberOf _ + * @category Utility + * @param {Object} object The object to query. + * @returns {Function} Returns the new function. + * @example + * + * var array = _.times(3, _.constant), + * object = { 'a': array, 'b': array, 'c': array }; + * + * _.map(['a[2]', 'c[0]'], _.methodOf(object)); + * // => [2, 0] + * + * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); + * // => [2, 0] + */ + var methodOf = restParam(function(object, args) { + return function(path) { + return invokePath(object, path, args); + }; + }); + /** * Adds all own enumerable function properties of a source object to the * destination object. If `object` is a function then methods are added to * its prototype as well. * - * **Note:** Use `_.runInContext` to create a pristine `lodash` function - * for mixins to avoid conflicts caused by modifying the original. + * **Note:** Use `_.runInContext` to create a pristine `lodash` function to + * avoid conflicts caused by modifying the original. * * @static * @memberOf _ * @category Utility - * @param {Function|Object} [object=this] object The destination object. + * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options] The options object. * @param {boolean} [options.chain=true] Specify whether the functions added @@ -10931,61 +11290,61 @@ } /** - * Creates a function which returns the property value of `key` on a given object. + * Creates a function which returns the property value at `path` on a + * given object. * * @static * @memberOf _ * @category Utility - * @param {string} key The key of the property to get. + * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * - * var users = [ - * { 'user': 'fred' }, - * { 'user': 'barney' } + * var objects = [ + * { 'a': { 'b': { 'c': 2 } } }, + * { 'a': { 'b': { 'c': 1 } } } * ]; * - * var getName = _.property('user'); + * _.map(objects, _.property('a.b.c')); + * // => [2, 1] * - * _.map(users, getName); - * // => ['fred', 'barney'] - * - * _.pluck(_.sortBy(users, getName), 'user'); - * // => ['barney', 'fred'] + * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); + * // => [1, 2] */ - function property(key) { - return baseProperty(key + ''); + function property(path) { + return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function which returns - * the property value of a given key on `object`. + * the property value at a given path on `object`. * * @static * @memberOf _ * @category Utility - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Function} Returns the new function. * @example * - * var object = { 'a': 3, 'b': 1, 'c': 2 }; + * var array = [0, 1, 2], + * object = { 'a': array, 'b': array, 'c': array }; * - * _.map(['a', 'c'], _.propertyOf(object)); - * // => [3, 2] + * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); + * // => [2, 0] * - * _.sortBy(['a', 'b', 'c'], _.propertyOf(object)); - * // => ['b', 'c', 'a'] + * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); + * // => [2, 0] */ function propertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; + return function(path) { + return baseGet(object, toPath(path), 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 is - * set to `start` with `start` then set to `0`. If `start` is less than `end` + * 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. * * @static @@ -11061,7 +11420,7 @@ * _.times(3, function(n) { * mage.castSpell(n); * }); - * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` respectively + * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` * * _.times(3, function(n) { * this.cast(n); @@ -11069,7 +11428,7 @@ * // => also invokes `mage.castSpell(n)` three times */ function times(n, iteratee, thisArg) { - n = +n; + n = floor(n); // Exit early to avoid a JSC JIT bug in Safari 8 // where `Array(0)` is treated as `Array(1)`. @@ -11128,7 +11487,7 @@ * // => 10 */ function add(augend, addend) { - return augend + addend; + return (+augend || 0) + (+addend || 0); } /** @@ -11354,6 +11713,8 @@ lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; + lodash.method = method; + lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.omit = omit; @@ -11374,6 +11735,7 @@ lodash.remove = remove; lodash.rest = rest; lodash.restParam = restParam; + lodash.set = set; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; @@ -11442,6 +11804,7 @@ lodash.findLastKey = findLastKey; lodash.findWhere = findWhere; lodash.first = first; + lodash.get = get; lodash.has = has; lodash.identity = identity; lodash.includes = includes; @@ -11630,7 +11993,7 @@ // Add `LazyWrapper` methods for `_.pluck` and `_.where`. arrayEach(['pluck', 'where'], function(methodName, index) { var operationName = index ? 'filter' : 'map', - createCallback = index ? baseMatches : baseProperty; + createCallback = index ? baseMatches : property; LazyWrapper.prototype[methodName] = function(value) { return this[operationName](createCallback(value)); @@ -11652,7 +12015,7 @@ start = start == null ? 0 : (+start || 0); var result = start < 0 ? this.takeRight(-start) : this.drop(start); - if (typeof end != 'undefined') { + if (end !== undefined) { end = (+end || 0); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } @@ -11683,7 +12046,7 @@ useLazy = isLazy || isArray(value); if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { - // avoid lazy use if the iteratee has a `length` other than `1` + // avoid lazy use if the iteratee has a "length" value other than `1` isLazy = useLazy = false; } var onlyLazy = isLazy && !isHybrid; diff --git a/math/add.js b/math/add.js index aeef3402a..2bf7087c0 100644 --- a/math/add.js +++ b/math/add.js @@ -15,7 +15,7 @@ define([], function() { * // => 10 */ function add(augend, addend) { - return augend + addend; + return (+augend || 0) + (+addend || 0); } return add; diff --git a/number/inRange.js b/number/inRange.js index 4854fefb2..9c74c28b2 100644 --- a/number/inRange.js +++ b/number/inRange.js @@ -1,5 +1,9 @@ define([], function() { + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeMax = Math.max, + nativeMin = Math.min; + /** * Checks if `n` is between `start` and up to but not including, `end`. If * `end` is not specified it is set to `start` with `start` then set to `0`. @@ -39,7 +43,7 @@ define([], function() { } else { end = +end || 0; } - return value >= start && value < end; + return value >= nativeMin(start, end) && value < nativeMax(start, end); } return inRange; diff --git a/object.js b/object.js index 8b31af73d..ef7932b7c 100644 --- a/object.js +++ b/object.js @@ -1,4 +1,4 @@ -define(['./object/assign', './object/create', './object/defaults', './object/extend', './object/findKey', './object/findLastKey', './object/forIn', './object/forInRight', './object/forOwn', './object/forOwnRight', './object/functions', './object/has', './object/invert', './object/keys', './object/keysIn', './object/mapValues', './object/merge', './object/methods', './object/omit', './object/pairs', './object/pick', './object/result', './object/transform', './object/values', './object/valuesIn'], function(assign, create, defaults, extend, findKey, findLastKey, forIn, forInRight, forOwn, forOwnRight, functions, has, invert, keys, keysIn, mapValues, merge, methods, omit, pairs, pick, result, transform, values, valuesIn) { +define(['./object/assign', './object/create', './object/defaults', './object/extend', './object/findKey', './object/findLastKey', './object/forIn', './object/forInRight', './object/forOwn', './object/forOwnRight', './object/functions', './object/get', './object/has', './object/invert', './object/keys', './object/keysIn', './object/mapValues', './object/merge', './object/methods', './object/omit', './object/pairs', './object/pick', './object/result', './object/set', './object/transform', './object/values', './object/valuesIn'], function(assign, create, defaults, extend, findKey, findLastKey, forIn, forInRight, forOwn, forOwnRight, functions, get, has, invert, keys, keysIn, mapValues, merge, methods, omit, pairs, pick, result, set, transform, values, valuesIn) { return { 'assign': assign, 'create': create, @@ -11,6 +11,7 @@ define(['./object/assign', './object/create', './object/defaults', './object/ext 'forOwn': forOwn, 'forOwnRight': forOwnRight, 'functions': functions, + 'get': get, 'has': has, 'invert': invert, 'keys': keys, @@ -22,6 +23,7 @@ define(['./object/assign', './object/create', './object/defaults', './object/ext 'pairs': pairs, 'pick': pick, 'result': result, + 'set': set, 'transform': transform, 'values': values, 'valuesIn': valuesIn diff --git a/object/assign.js b/object/assign.js index c218d7bd6..fe58629a8 100644 --- a/object/assign.js +++ b/object/assign.js @@ -1,4 +1,4 @@ -define(['../internal/baseAssign', '../internal/createAssigner'], function(baseAssign, createAssigner) { +define(['../internal/assignWith', '../internal/baseAssign', '../internal/createAssigner'], function(assignWith, baseAssign, createAssigner) { /** * Assigns own enumerable properties of source object(s) to the destination @@ -7,13 +7,17 @@ define(['../internal/baseAssign', '../internal/createAssigner'], function(baseAs * The `customizer` is bound to `thisArg` and invoked with five arguments: * (objectValue, sourceValue, key, object, source). * + * **Note:** This method mutates `object` and is based on + * [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). + * + * * @static * @memberOf _ * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. - * @param {Function} [customizer] The function to customize assigning values. + * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example @@ -23,13 +27,17 @@ define(['../internal/baseAssign', '../internal/createAssigner'], function(baseAs * * // using a customizer callback * var defaults = _.partialRight(_.assign, function(value, other) { - * return typeof value == 'undefined' ? other : value; + * return _.isUndefined(value) ? other : value; * }); * * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ - var assign = createAssigner(baseAssign); + var assign = createAssigner(function(object, source, customizer) { + return customizer + ? assignWith(object, source, customizer) + : baseAssign(object, source); + }); return assign; }); diff --git a/object/create.js b/object/create.js index dc4f56b26..e0da500ea 100644 --- a/object/create.js +++ b/object/create.js @@ -1,4 +1,4 @@ -define(['../internal/baseCopy', '../internal/baseCreate', '../internal/isIterateeCall', './keys'], function(baseCopy, baseCreate, isIterateeCall, keys) { +define(['../internal/baseAssign', '../internal/baseCreate', '../internal/isIterateeCall'], function(baseAssign, baseCreate, isIterateeCall) { /** * Creates an object that inherits from the given `prototype` object. If a @@ -39,7 +39,7 @@ define(['../internal/baseCopy', '../internal/baseCreate', '../internal/isIterate if (guard && isIterateeCall(prototype, properties, guard)) { properties = null; } - return properties ? baseCopy(properties, result, keys(properties)) : result; + return properties ? baseAssign(result, properties) : result; } return create; diff --git a/object/defaults.js b/object/defaults.js index 87d4abc9d..ab394a990 100644 --- a/object/defaults.js +++ b/object/defaults.js @@ -8,6 +8,8 @@ define(['./assign', '../internal/assignDefaults', '../function/restParam'], func * object for all destination properties that resolve to `undefined`. Once a * property is set, additional values of the same property are ignored. * + * **Note:** This method mutates `object`. + * * @static * @memberOf _ * @category Object diff --git a/object/forIn.js b/object/forIn.js index 1843392b5..be2ebdb23 100644 --- a/object/forIn.js +++ b/object/forIn.js @@ -3,7 +3,7 @@ define(['../internal/baseFor', '../internal/createForIn'], function(baseFor, cre /** * 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). Iterator functions may exit + * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static diff --git a/object/forOwn.js b/object/forOwn.js index 71a7c1364..7c722a634 100644 --- a/object/forOwn.js +++ b/object/forOwn.js @@ -3,7 +3,7 @@ define(['../internal/baseForOwn', '../internal/createForOwn'], function(baseForO /** * 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). Iterator functions may exit iteration + * three arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static diff --git a/object/get.js b/object/get.js new file mode 100644 index 000000000..d9b5a5d26 --- /dev/null +++ b/object/get.js @@ -0,0 +1,36 @@ +define(['../internal/baseGet', '../internal/toPath'], function(baseGet, toPath) { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** + * Gets the property value of `path` on `object`. If the resolved value is + * `undefined` the `defaultValue` is used in its place. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, toPath(path), path + ''); + return result === undefined ? defaultValue : result; + } + + return get; +}); diff --git a/object/has.js b/object/has.js index 51b1200a4..38cd782c5 100644 --- a/object/has.js +++ b/object/has.js @@ -1,4 +1,4 @@ -define([], function() { +define(['../internal/baseGet', '../internal/baseSlice', '../internal/isKey', '../array/last', '../internal/toPath'], function(baseGet, baseSlice, isKey, last, toPath) { /** Used for native method references. */ var objectProto = Object.prototype; @@ -7,24 +7,39 @@ define([], function() { var hasOwnProperty = objectProto.hasOwnProperty; /** - * Checks if `key` exists as a direct property of `object` instead of an - * inherited property. + * Checks if `path` is a direct property. * * @static * @memberOf _ * @category Object - * @param {Object} object The object to inspect. - * @param {string} key The key to check. - * @returns {boolean} Returns `true` if `key` is a direct property, else `false`. + * @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`. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 3 }; + * var object = { 'a': { 'b': { 'c': 3 } } }; * - * _.has(object, 'b'); + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b.c'); + * // => true + * + * _.has(object, ['a', 'b', 'c']); * // => true */ - function has(object, key) { - return object ? hasOwnProperty.call(object, key) : 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)); + path = last(path); + result = object != null && hasOwnProperty.call(object, path); + } + return result; } return has; diff --git a/object/keys.js b/object/keys.js index 6fdcd212f..db04cb7d4 100644 --- a/object/keys.js +++ b/object/keys.js @@ -13,7 +13,7 @@ define(['../internal/isLength', '../lang/isNative', '../lang/isObject', '../inte * @static * @memberOf _ * @category Object - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * @@ -36,7 +36,7 @@ define(['../internal/isLength', '../lang/isNative', '../lang/isObject', '../inte length = object.length; } if ((typeof Ctor == 'function' && Ctor.prototype === object) || - (typeof object != 'function' && (length && isLength(length)))) { + (typeof object != 'function' && isLength(length))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; diff --git a/object/keysIn.js b/object/keysIn.js index 8da02f6ed..6fbd497d5 100644 --- a/object/keysIn.js +++ b/object/keysIn.js @@ -14,7 +14,7 @@ define(['../lang/isArguments', '../lang/isArray', '../internal/isIndex', '../int * @static * @memberOf _ * @category Object - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * diff --git a/object/merge.js b/object/merge.js index 0b89bd35e..687337451 100644 --- a/object/merge.js +++ b/object/merge.js @@ -14,7 +14,7 @@ define(['../internal/baseMerge', '../internal/createAssigner'], function(baseMer * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. - * @param {Function} [customizer] The function to customize merging properties. + * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example diff --git a/object/pairs.js b/object/pairs.js index 1b07805fc..b5fc5c311 100644 --- a/object/pairs.js +++ b/object/pairs.js @@ -7,7 +7,7 @@ define(['./keys'], function(keys) { * @static * @memberOf _ * @category Object - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * diff --git a/object/result.js b/object/result.js index db2064df3..f35f2dcc9 100644 --- a/object/result.js +++ b/object/result.js @@ -1,44 +1,47 @@ -define(['../lang/isFunction'], function(isFunction) { +define(['../internal/baseGet', '../internal/baseSlice', '../lang/isFunction', '../internal/isKey', '../array/last', '../internal/toPath'], function(baseGet, baseSlice, isFunction, isKey, last, toPath) { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** - * Resolves the value of property `key` on `object`. If the value of `key` is - * a function it is invoked with the `this` binding of `object` and its result - * is returned, else the property value is returned. If the property value is - * `undefined` the `defaultValue` is used in its place. + * This method is like `_.get` except that if the resolved value is a function + * it is invoked with the `this` binding of its parent object and its result + * is returned. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. - * @param {string} key The key of the property to resolve. - * @param {*} [defaultValue] The value returned if the property value - * resolves to `undefined`. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * - * var object = { 'user': 'fred', 'age': _.constant(40) }; + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * - * _.result(object, 'user'); - * // => 'fred' + * _.result(object, 'a[0].b.c1'); + * // => 3 * - * _.result(object, 'age'); - * // => 40 + * _.result(object, 'a[0].b.c2'); + * // => 4 * - * _.result(object, 'status', 'busy'); - * // => 'busy' + * _.result(object, 'a.b.c', 'default'); + * // => 'default' * - * _.result(object, 'status', _.constant('busy')); - * // => 'busy' + * _.result(object, 'a.b.c', _.constant('default')); + * // => 'default' */ - function result(object, key, defaultValue) { - var value = object == null ? undefined : object[key]; - if (typeof value == 'undefined') { - value = defaultValue; + function result(object, path, defaultValue) { + var 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; } - return isFunction(value) ? value.call(object) : value; + return isFunction(result) ? result.call(object) : result; } return result; diff --git a/object/set.js b/object/set.js new file mode 100644 index 000000000..d02c34e7b --- /dev/null +++ b/object/set.js @@ -0,0 +1,53 @@ +define(['../internal/isIndex', '../internal/isKey', '../lang/isObject', '../internal/toPath'], function(isIndex, isKey, isObject, toPath) { + + /** + * Sets the property value of `path` on `object`. If a portion of `path` + * does not exist it is created. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to augment. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, 'x[0].y.z', 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + if (object == null) { + return object; + } + var pathKey = (path + ''); + path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path); + + var index = -1, + length = path.length, + endIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = path[index]; + if (isObject(nested)) { + if (index == endIndex) { + nested[key] = value; + } else if (nested[key] == null) { + nested[key] = isIndex(path[index + 1]) ? [] : {}; + } + } + nested = nested[key]; + } + return object; + } + + return set; +}); diff --git a/object/transform.js b/object/transform.js index 4f9f1d61a..612c71eed 100644 --- a/object/transform.js +++ b/object/transform.js @@ -5,7 +5,7 @@ define(['../internal/arrayEach', '../internal/baseCallback', '../internal/baseCr * `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). Iterator functions + * with four arguments: (accumulator, value, key, object). Iteratee functions * may exit iteration early by explicitly returning `false`. * * @static diff --git a/package.json b/package.json index 7666ddef3..5b558fec6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lodash", - "version": "3.6.0", + "version": "3.7.0", "main": "main.js", "private": true, "volo": { diff --git a/string/deburr.js b/string/deburr.js index 89886b12f..b5e423921 100644 --- a/string/deburr.js +++ b/string/deburr.js @@ -1,9 +1,7 @@ define(['../internal/baseToString', '../internal/deburrLetter'], function(baseToString, deburrLetter) { - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - */ - var reComboMarks = /[\u0300-\u036f\ufe20-\ufe23]/g; + /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */ + var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g; /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; @@ -24,7 +22,7 @@ define(['../internal/baseToString', '../internal/deburrLetter'], function(baseTo */ function deburr(string) { string = baseToString(string); - return string && string.replace(reLatin1, deburrLetter).replace(reComboMarks, ''); + return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } return deburr; diff --git a/string/endsWith.js b/string/endsWith.js index 64d9e4991..999daf554 100644 --- a/string/endsWith.js +++ b/string/endsWith.js @@ -1,5 +1,8 @@ define(['../internal/baseToString'], function(baseToString) { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /* Native method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; @@ -29,7 +32,7 @@ define(['../internal/baseToString'], function(baseToString) { target = (target + ''); var length = string.length; - position = typeof position == 'undefined' + position = position === undefined ? length : nativeMin(position < 0 ? 0 : (+position || 0), length); diff --git a/string/escape.js b/string/escape.js index 35ca75970..076352d72 100644 --- a/string/escape.js +++ b/string/escape.js @@ -18,9 +18,10 @@ define(['../internal/baseToString', '../internal/escapeHtmlChar'], function(base * (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 [#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. + * 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. * * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping) * to reduce XSS vectors. diff --git a/string/parseInt.js b/string/parseInt.js index 9aab52701..992940db4 100644 --- a/string/parseInt.js +++ b/string/parseInt.js @@ -1,7 +1,7 @@ define(['../internal/isIterateeCall', '../internal/root', './trim'], function(isIterateeCall, root, trim) { /** Used to detect hexadecimal string values. */ - var reHexPrefix = /^0[xX]/; + var reHasHexPrefix = /^0[xX]/; /** Used to detect and test for whitespace. */ var whitespace = ( @@ -59,7 +59,7 @@ define(['../internal/isIterateeCall', '../internal/root', './trim'], function(is radix = +radix; } string = trim(string); - return nativeParseInt(string, radix || (reHexPrefix.test(string) ? 16 : 10)); + return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); }; } diff --git a/string/template.js b/string/template.js index 73c9a3f07..b2e1cfd7c 100644 --- a/string/template.js +++ b/string/template.js @@ -1,4 +1,4 @@ -define(['../internal/assignOwnDefaults', '../utility/attempt', '../internal/baseAssign', '../internal/baseToString', '../internal/baseValues', '../internal/escapeStringChar', '../lang/isError', '../internal/isIterateeCall', '../object/keys', '../internal/reInterpolate', './templateSettings'], function(assignOwnDefaults, attempt, baseAssign, baseToString, baseValues, escapeStringChar, isError, isIterateeCall, keys, reInterpolate, templateSettings) { +define(['../internal/assignOwnDefaults', '../internal/assignWith', '../utility/attempt', '../internal/baseAssign', '../internal/baseToString', '../internal/baseValues', '../internal/escapeStringChar', '../lang/isError', '../internal/isIterateeCall', '../object/keys', '../internal/reInterpolate', './templateSettings'], function(assignOwnDefaults, assignWith, attempt, baseAssign, baseToString, baseValues, escapeStringChar, isError, isIterateeCall, keys, reInterpolate, templateSettings) { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; @@ -8,9 +8,7 @@ define(['../internal/assignOwnDefaults', '../utility/attempt', '../internal/base reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - /** - * Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). - */ + /** Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to ensure capturing order of template delimiters. */ @@ -124,9 +122,9 @@ define(['../internal/assignOwnDefaults', '../utility/attempt', '../internal/base options = otherOptions = null; } string = baseToString(string); - options = baseAssign(baseAssign({}, otherOptions || options), settings, assignOwnDefaults); + options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults); - var imports = baseAssign(baseAssign({}, options.imports), settings.imports, assignOwnDefaults), + var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); diff --git a/support.js b/support.js index 1e0f2cc93..ccc89202e 100644 --- a/support.js +++ b/support.js @@ -19,6 +19,12 @@ define(['./internal/root'], function(root) { var support = {}; (function(x) { + var Ctor = function() { this.x = x; }, + object = { '0': x, 'length': x }, + props = []; + + Ctor.prototype = { 'valueOf': x, 'y': x }; + for (var key in new Ctor) { props.push(key); } /** * Detect if functions can be decompiled by `Function#toString` @@ -56,8 +62,8 @@ define(['./internal/root'], function(root) { * In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object * indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat * `arguments` object indexes as non-enumerable and fail `hasOwnProperty` - * checks for indexes that exceed their function's formal parameters with - * associated values of `0`. + * checks for indexes that exceed the number of function parameters and + * whose associated argument values are `0`. * * @memberOf _.support * @type boolean @@ -67,7 +73,7 @@ define(['./internal/root'], function(root) { } catch(e) { support.nonEnumArgs = true; } - }(0, 0)); + }(1, 0)); return support; }); diff --git a/utility.js b/utility.js index fed788b3f..7a4b74e1a 100644 --- a/utility.js +++ b/utility.js @@ -1,4 +1,4 @@ -define(['./utility/attempt', './utility/callback', './utility/constant', './utility/identity', './utility/iteratee', './utility/matches', './utility/matchesProperty', './utility/mixin', './utility/noop', './utility/property', './utility/propertyOf', './utility/range', './utility/times', './utility/uniqueId'], function(attempt, callback, constant, identity, iteratee, matches, matchesProperty, mixin, noop, property, propertyOf, range, times, uniqueId) { +define(['./utility/attempt', './utility/callback', './utility/constant', './utility/identity', './utility/iteratee', './utility/matches', './utility/matchesProperty', './utility/method', './utility/methodOf', './utility/mixin', './utility/noop', './utility/property', './utility/propertyOf', './utility/range', './utility/times', './utility/uniqueId'], function(attempt, callback, constant, identity, iteratee, matches, matchesProperty, method, methodOf, mixin, noop, property, propertyOf, range, times, uniqueId) { return { 'attempt': attempt, 'callback': callback, @@ -7,6 +7,8 @@ define(['./utility/attempt', './utility/callback', './utility/constant', './util 'iteratee': iteratee, 'matches': matches, 'matchesProperty': matchesProperty, + 'method': method, + 'methodOf': methodOf, 'mixin': mixin, 'noop': noop, 'property': property, diff --git a/utility/callback.js b/utility/callback.js index 977de379c..993a62054 100644 --- a/utility/callback.js +++ b/utility/callback.js @@ -1,4 +1,4 @@ -define(['../internal/baseCallback', '../internal/isIterateeCall', '../internal/isObjectLike', './matches'], function(baseCallback, isIterateeCall, isObjectLike, matches) { +define(['../internal/baseCallback', '../internal/isIterateeCall'], function(baseCallback, isIterateeCall) { /** * Creates a function that invokes `func` with the `this` binding of `thisArg` @@ -42,9 +42,7 @@ define(['../internal/baseCallback', '../internal/isIterateeCall', '../internal/i if (guard && isIterateeCall(func, thisArg, guard)) { thisArg = null; } - return isObjectLike(func) - ? matches(func) - : baseCallback(func, thisArg); + return baseCallback(func, thisArg); } return callback; diff --git a/utility/matchesProperty.js b/utility/matchesProperty.js index 4c9a9722b..30755d0b6 100644 --- a/utility/matchesProperty.js +++ b/utility/matchesProperty.js @@ -1,7 +1,7 @@ define(['../internal/baseClone', '../internal/baseMatchesProperty'], function(baseClone, baseMatchesProperty) { /** - * Creates a function which compares the property value of `key` on a given + * Creates a function which compares the property value of `path` on a given * object to `value`. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, @@ -11,7 +11,7 @@ define(['../internal/baseClone', '../internal/baseMatchesProperty'], function(ba * @static * @memberOf _ * @category Utility - * @param {string} key The key of the property to get. + * @param {Array|string} path The path of the property to get. * @param {*} value The value to compare. * @returns {Function} Returns the new function. * @example @@ -24,8 +24,8 @@ define(['../internal/baseClone', '../internal/baseMatchesProperty'], function(ba * _.find(users, _.matchesProperty('user', 'fred')); * // => { 'user': 'fred' } */ - function matchesProperty(key, value) { - return baseMatchesProperty(key + '', baseClone(value, true)); + function matchesProperty(path, value) { + return baseMatchesProperty(path, baseClone(value, true)); } return matchesProperty; diff --git a/utility/method.js b/utility/method.js new file mode 100644 index 000000000..2d32d5504 --- /dev/null +++ b/utility/method.js @@ -0,0 +1,31 @@ +define(['../internal/invokePath', '../function/restParam'], function(invokePath, restParam) { + + /** + * Creates a function which invokes the method at `path` on a given object. + * + * @static + * @memberOf _ + * @category Utility + * @param {Array|string} path The path of the method to invoke. + * @returns {Function} Returns the new function. + * @example + * + * var objects = [ + * { 'a': { 'b': { 'c': _.constant(2) } } }, + * { 'a': { 'b': { 'c': _.constant(1) } } } + * ]; + * + * _.map(objects, _.method('a.b.c')); + * // => [2, 1] + * + * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c'); + * // => [1, 2] + */ + var method = restParam(function(path, args) { + return function(object) { + return invokePath(object, path, args); + } + }); + + return method; +}); diff --git a/utility/methodOf.js b/utility/methodOf.js new file mode 100644 index 000000000..0768af70c --- /dev/null +++ b/utility/methodOf.js @@ -0,0 +1,30 @@ +define(['../internal/invokePath', '../function/restParam'], function(invokePath, restParam) { + + /** + * The opposite of `_.method`; this method creates a function which invokes + * the method at a given path on `object`. + * + * @static + * @memberOf _ + * @category Utility + * @param {Object} object The object to query. + * @returns {Function} Returns the new function. + * @example + * + * var array = _.times(3, _.constant), + * object = { 'a': array, 'b': array, 'c': array }; + * + * _.map(['a[2]', 'c[0]'], _.methodOf(object)); + * // => [2, 0] + * + * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); + * // => [2, 0] + */ + var methodOf = restParam(function(object, args) { + return function(path) { + return invokePath(object, path, args); + }; + }); + + return methodOf; +}); diff --git a/utility/mixin.js b/utility/mixin.js index 28cdaa2fb..ad115e5a5 100644 --- a/utility/mixin.js +++ b/utility/mixin.js @@ -11,13 +11,13 @@ define(['../internal/arrayCopy', '../internal/baseFunctions', '../lang/isFunctio * destination object. If `object` is a function then methods are added to * its prototype as well. * - * **Note:** Use `_.runInContext` to create a pristine `lodash` function - * for mixins to avoid conflicts caused by modifying the original. + * **Note:** Use `_.runInContext` to create a pristine `lodash` function to + * avoid conflicts caused by modifying the original. * * @static * @memberOf _ * @category Utility - * @param {Function|Object} [object=this] object The destination object. + * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options] The options object. * @param {boolean} [options.chain=true] Specify whether the functions added diff --git a/utility/property.js b/utility/property.js index d6cb72fb1..e84a7ca4a 100644 --- a/utility/property.js +++ b/utility/property.js @@ -1,30 +1,29 @@ -define(['../internal/baseProperty'], function(baseProperty) { +define(['../internal/baseProperty', '../internal/basePropertyDeep', '../internal/isKey'], function(baseProperty, basePropertyDeep, isKey) { /** - * Creates a function which returns the property value of `key` on a given object. + * Creates a function which returns the property value at `path` on a + * given object. * * @static * @memberOf _ * @category Utility - * @param {string} key The key of the property to get. + * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * - * var users = [ - * { 'user': 'fred' }, - * { 'user': 'barney' } + * var objects = [ + * { 'a': { 'b': { 'c': 2 } } }, + * { 'a': { 'b': { 'c': 1 } } } * ]; * - * var getName = _.property('user'); + * _.map(objects, _.property('a.b.c')); + * // => [2, 1] * - * _.map(users, getName); - * // => ['fred', 'barney'] - * - * _.pluck(_.sortBy(users, getName), 'user'); - * // => ['barney', 'fred'] + * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); + * // => [1, 2] */ - function property(key) { - return baseProperty(key + ''); + function property(path) { + return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } return property; diff --git a/utility/propertyOf.js b/utility/propertyOf.js index d506237df..91fdf6f03 100644 --- a/utility/propertyOf.js +++ b/utility/propertyOf.js @@ -1,30 +1,28 @@ -define([], function() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; +define(['../internal/baseGet', '../internal/toPath'], function(baseGet, toPath) { /** * The opposite of `_.property`; this method creates a function which returns - * the property value of a given key on `object`. + * the property value at a given path on `object`. * * @static * @memberOf _ * @category Utility - * @param {Object} object The object to inspect. + * @param {Object} object The object to query. * @returns {Function} Returns the new function. * @example * - * var object = { 'a': 3, 'b': 1, 'c': 2 }; + * var array = [0, 1, 2], + * object = { 'a': array, 'b': array, 'c': array }; * - * _.map(['a', 'c'], _.propertyOf(object)); - * // => [3, 2] + * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); + * // => [2, 0] * - * _.sortBy(['a', 'b', 'c'], _.propertyOf(object)); - * // => ['b', 'c', 'a'] + * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); + * // => [2, 0] */ function propertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; + return function(path) { + return baseGet(object, toPath(path), path + ''); }; } diff --git a/utility/range.js b/utility/range.js index 9bfeaf876..ab6825f36 100644 --- a/utility/range.js +++ b/utility/range.js @@ -9,7 +9,7 @@ define(['../internal/isIterateeCall'], function(isIterateeCall) { /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. If `end` is not specified it is - * set to `start` with `start` then set to `0`. If `start` is less than `end` + * 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. * * @static diff --git a/utility/times.js b/utility/times.js index 04fa99d6b..6304ae532 100644 --- a/utility/times.js +++ b/utility/times.js @@ -1,5 +1,8 @@ define(['../internal/bindCallback', '../internal/root'], function(bindCallback, root) { + /** Native method references. */ + var floor = Math.floor; + /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = root.isFinite, nativeMin = Math.min; @@ -27,7 +30,7 @@ define(['../internal/bindCallback', '../internal/root'], function(bindCallback, * _.times(3, function(n) { * mage.castSpell(n); * }); - * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` respectively + * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` * * _.times(3, function(n) { * this.cast(n); @@ -35,7 +38,7 @@ define(['../internal/bindCallback', '../internal/root'], function(bindCallback, * // => also invokes `mage.castSpell(n)` three times */ function times(n, iteratee, thisArg) { - n = +n; + n = floor(n); // Exit early to avoid a JSC JIT bug in Safari 8 // where `Array(0)` is treated as `Array(1)`.