diff --git a/README.md b/README.md index 9838613f8..119b94cbc 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 [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) modules. @@ -28,7 +28,7 @@ var array = require('lodash/array'); var chunk = require('lodash/array/chunk'); ``` -See the [package source](https://github.com/lodash/lodash/tree/3.6.0-npm) for more details. +See the [package source](https://github.com/lodash/lodash/tree/3.7.0-npm) for more details. **Note:**
Don’t assign values to the [special variable](http://nodejs.org/api/repl.html#repl_repl_features) `_` when in the REPL.
@@ -39,8 +39,8 @@ Install [n_](https://www.npmjs.com/package/n_) for a REPL that includes lodash b lodash is also available in a variety of other builds & module formats. * npm packages for [modern](https://www.npmjs.com/package/lodash), [compatibility](https://www.npmjs.com/package/lodash-compat), & [per method](https://www.npmjs.com/browse/keyword/lodash-modularized) builds - * AMD modules for [modern](https://github.com/lodash/lodash/tree/3.6.0-amd) & [compatibility](https://github.com/lodash/lodash-compat/tree/3.6.0-amd) builds - * ES modules for the [modern](https://github.com/lodash/lodash/tree/3.6.0-es) build + * AMD modules for [modern](https://github.com/lodash/lodash/tree/3.7.0-amd) & [compatibility](https://github.com/lodash/lodash-compat/tree/3.7.0-amd) builds + * ES modules for the [modern](https://github.com/lodash/lodash/tree/3.7.0-es) build ## Further Reading @@ -75,12 +75,14 @@ lodash is also available in a variety of other builds & module formats. * [_.forEach](https://lodash.com/docs#forEach) supports exiting early * [_.forIn](https://lodash.com/docs#forIn) for iterating all enumerable properties * [_.forOwn](https://lodash.com/docs#forOwn) for iterating own properties + * [_.get](https://lodash.com/docs#get) & [_.set](https://lodash.com/docs#set) for deep property getting & setting * [_.inRange](https://lodash.com/docs#inRange) for checking whether a number is within a given range * [_.isNative](https://lodash.com/docs#isNative) to check for native functions * [_.isPlainObject](https://lodash.com/docs#isPlainObject) & [_.toPlainObject](https://lodash.com/docs#toPlainObject) to check for & convert to `Object` objects * [_.isTypedArray](https://lodash.com/docs#isTypedArray) to check for typed arrays * [_.matches](https://lodash.com/docs#matches) supports deep object comparisons * [_.matchesProperty](https://lodash.com/docs#matchesProperty) to complement [_.matches](https://lodash.com/docs#matches) & [_.property](https://lodash.com/docs#property) + * [_.method](https://lodash.com/docs#method) & [_.methodOf](https://lodash.com/docs#methodOf) to create functions that invoke methods * [_.merge](https://lodash.com/docs#merge) for a deep [_.extend](https://lodash.com/docs#extend) * [_.parseInt](https://lodash.com/docs#parseInt) for consistent cross-environment behavior * [_.pull](https://lodash.com/docs#pull), [_.pullAt](https://lodash.com/docs#pullAt), & [_.remove](https://lodash.com/docs#remove) for mutating arrays @@ -112,5 +114,5 @@ lodash is also available in a variety of other builds & module formats. ## Support -Tested in Chrome 40-41, Firefox 35-36, IE 6-11, Opera 27-28, Safari 5-8, io.js 1.6.2, Node.js 0.8.28, 0.10.36, & 0.12.0, PhantomJS 1.9.8, RingoJS 0.11, & Rhino 1.7RC5. +Tested in Chrome 41-42, Firefox 36-37, IE 6-11, Opera 27-28, Safari 5-8, io.js 1.7.1, Node.js 0.8.28, 0.10.38, & 0.12.2, PhantomJS 1.9.8, RingoJS 0.11, & Rhino 1.7RC5. Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. Special thanks to [Sauce Labs](https://saucelabs.com/) for providing automated browser testing. diff --git a/array/intersection.js b/array/intersection.js index 5df24fd2e..c8ce09dc8 100644 --- a/array/intersection.js +++ b/array/intersection.js @@ -27,7 +27,8 @@ function intersection() { argsLength = arguments.length, caches = [], indexOf = baseIndexOf, - isCommon = true; + isCommon = true, + result = []; while (++argsIndex < argsLength) { var value = arguments[argsIndex]; @@ -37,10 +38,12 @@ function intersection() { } } 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 e48e1c443..da0e5874e 100644 --- a/array/pullAt.js +++ b/array/pullAt.js @@ -1,15 +1,9 @@ var baseAt = require('../internal/baseAt'), baseCompareAscending = require('../internal/baseCompareAscending'), baseFlatten = require('../internal/baseFlatten'), - isIndex = require('../internal/isIndex'), + basePullAt = require('../internal/basePullAt'), restParam = require('../function/restParam'); -/** Used for native method references. */ -var arrayProto = Array.prototype; - -/** Native method references. */ -var splice = arrayProto.splice; - /** * Removes elements from `array` corresponding to the given indexes and returns * an array of the removed elements. Indexes may be specified as an array of @@ -39,17 +33,8 @@ var pullAt = restParam(function(array, indexes) { 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 ea2f2cc2d..0cf979bda 100644 --- a/array/remove.js +++ b/array/remove.js @@ -1,10 +1,5 @@ -var baseCallback = require('../internal/baseCallback'); - -/** Used for native method references. */ -var arrayProto = Array.prototype; - -/** Native method references. */ -var splice = arrayProto.splice; +var baseCallback = require('../internal/baseCallback'), + basePullAt = require('../internal/basePullAt'); /** * Removes all elements from `array` that `predicate` returns truthy for @@ -46,19 +41,23 @@ var splice = arrayProto.splice; * // => [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 ee6fb7395..48ef1a1a2 100644 --- a/array/slice.js +++ b/array/slice.js @@ -4,7 +4,7 @@ var baseSlice = require('../internal/baseSlice'), /** * 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 e34213a22..2c9fabadf 100644 --- a/array/uniq.js +++ b/array/uniq.js @@ -4,12 +4,13 @@ var baseCallback = require('../internal/baseCallback'), sortedUniq = require('../internal/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. @@ -37,8 +38,8 @@ var baseCallback = require('../internal/baseCallback'), * @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 f7f855848..5d28c9be6 100644 --- a/array/unzip.js +++ b/array/unzip.js @@ -1,9 +1,7 @@ var arrayMap = require('../internal/arrayMap'), arrayMax = require('../internal/arrayMax'), - baseProperty = require('../internal/baseProperty'); - -/** Used to the length of n-tuples for `_.unzip`. */ -var getLength = baseProperty('length'); + baseProperty = require('../internal/baseProperty'), + getLength = require('../internal/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 8ac40aeec..7ca104c44 100644 --- a/chain/lodash.js +++ b/chain/lodash.js @@ -50,8 +50,8 @@ var hasOwnProperty = objectProto.hasOwnProperty; * `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`, @@ -65,15 +65,15 @@ var hasOwnProperty = objectProto.hasOwnProperty; * `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. @@ -88,8 +88,8 @@ var hasOwnProperty = objectProto.hasOwnProperty; * 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 f99141a9f..753f4eabb 100644 --- a/collection/at.js +++ b/collection/at.js @@ -1,5 +1,6 @@ var baseAt = require('../internal/baseAt'), baseFlatten = require('../internal/baseFlatten'), + getLength = require('../internal/getLength'), isLength = require('../internal/isLength'), restParam = require('../function/restParam'), toIterable = require('../internal/toIterable'); @@ -25,7 +26,7 @@ var baseAt = require('../internal/baseAt'), * // => ['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 82a598cdf..a04d3db63 100644 --- a/collection/every.js +++ b/collection/every.js @@ -57,7 +57,7 @@ function every(collection, predicate, thisArg) { 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 c899d91cf..05a8e2140 100644 --- a/collection/forEach.js +++ b/collection/forEach.js @@ -5,10 +5,10 @@ var arrayEach = require('../internal/arrayEach'), /** * 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 76da61d46..dcf6f20cf 100644 --- a/collection/includes.js +++ b/collection/includes.js @@ -1,4 +1,5 @@ var baseIndexOf = require('../internal/baseIndexOf'), + getLength = require('../internal/getLength'), isArray = require('../lang/isArray'), isIterateeCall = require('../internal/isIterateeCall'), isLength = require('../internal/isLength'), @@ -41,7 +42,7 @@ var nativeMax = Math.max; * // => 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 a45463d4d..d68fa33bb 100644 --- a/collection/invoke.js +++ b/collection/invoke.js @@ -1,18 +1,21 @@ var baseEach = require('../internal/baseEach'), + getLength = require('../internal/getLength'), + invokePath = require('../internal/invokePath'), + isKey = require('../internal/isKey'), isLength = require('../internal/isLength'), restParam = require('../function/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. @@ -24,15 +27,16 @@ var baseEach = require('../internal/baseEach'), * _.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 f216fa222..cc337bcd5 100644 --- a/collection/map.js +++ b/collection/map.js @@ -35,7 +35,6 @@ var arrayMap = require('../internal/arrayMap'), * @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 af85d5a9a..5ee1ec84e 100644 --- a/collection/pluck.js +++ b/collection/pluck.js @@ -1,14 +1,14 @@ -var baseProperty = require('../internal/baseProperty'), - map = require('./map'); +var map = require('./map'), + property = require('../utility/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 * @@ -24,8 +24,8 @@ var baseProperty = require('../internal/baseProperty'), * _.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)); } module.exports = pluck; diff --git a/collection/reduce.js b/collection/reduce.js index e89781fb9..a483d2568 100644 --- a/collection/reduce.js +++ b/collection/reduce.js @@ -27,8 +27,8 @@ var arrayReduce = require('../internal/arrayReduce'), * @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 2db4bcfd2..78dcf4ce9 100644 --- a/collection/size.js +++ b/collection/size.js @@ -1,4 +1,5 @@ -var isLength = require('../internal/isLength'), +var getLength = require('../internal/getLength'), + isLength = require('../internal/isLength'), keys = require('../object/keys'); /** @@ -22,7 +23,7 @@ var isLength = require('../internal/isLength'), * // => 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 b1cba1fdb..2b866b464 100644 --- a/collection/some.js +++ b/collection/some.js @@ -58,7 +58,7 @@ function some(collection, predicate, thisArg) { 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 c64231da5..28d75f56d 100644 --- a/collection/sortBy.js +++ b/collection/sortBy.js @@ -1,9 +1,8 @@ var baseCallback = require('../internal/baseCallback'), - baseEach = require('../internal/baseEach'), + baseMap = require('../internal/baseMap'), baseSortBy = require('../internal/baseSortBy'), compareAscending = require('../internal/compareAscending'), - isIterateeCall = require('../internal/isIterateeCall'), - isLength = require('../internal/isLength'); + isIterateeCall = require('../internal/isIterateeCall'); /** * Creates an array of elements, sorted in ascending order by the results of @@ -27,9 +26,8 @@ var baseCallback = require('../internal/baseCallback'), * @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 @@ -58,16 +56,14 @@ function sortBy(collection, iteratee, thisArg) { 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 cd72c45b8..4766c2098 100644 --- a/collection/sortByAll.js +++ b/collection/sortByAll.js @@ -1,48 +1,52 @@ var baseFlatten = require('../internal/baseFlatten'), baseSortByOrder = require('../internal/baseSortByOrder'), - isIterateeCall = require('../internal/isIterateeCall'); + isIterateeCall = require('../internal/isIterateeCall'), + restParam = require('../function/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), []); +}); module.exports = sortByAll; diff --git a/collection/sortByOrder.js b/collection/sortByOrder.js index 4528e6db9..c704eeb61 100644 --- a/collection/sortByOrder.js +++ b/collection/sortByOrder.js @@ -4,45 +4,52 @@ var baseSortByOrder = require('../internal/baseSortByOrder'), /** * 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); } module.exports = sortByOrder; diff --git a/function/before.js b/function/before.js index 0ae3f972f..4afd1e60a 100644 --- a/function/before.js +++ b/function/before.js @@ -31,7 +31,8 @@ function before(n, func) { 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 22e20e92a..0de126ae3 100644 --- a/function/bind.js +++ b/function/bind.js @@ -14,7 +14,7 @@ var BIND_FLAG = 1, * 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 e2f47f9f6..a09e94852 100644 --- a/function/bindAll.js +++ b/function/bindAll.js @@ -12,7 +12,7 @@ var BIND_FLAG = 1; * 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 0307d24f2..b787fe702 100644 --- a/function/bindKey.js +++ b/function/bindKey.js @@ -13,7 +13,7 @@ var BIND_FLAG = 1, * * 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 37cb17f6b..b7db3fdad 100644 --- a/function/curry.js +++ b/function/curry.js @@ -13,7 +13,7 @@ var CURRY_FLAG = 8; * 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 f2586b046..11c540393 100644 --- a/function/curryRight.js +++ b/function/curryRight.js @@ -10,7 +10,7 @@ var CURRY_RIGHT_FLAG = 16; * 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 96ef5d170..0b5bd853c 100644 --- a/function/once.js +++ b/function/once.js @@ -18,7 +18,7 @@ var before = require('./before'); * // `initialize` invokes `createApplication` once */ function once(func) { - return before(func, 2); + return before(2, func); } module.exports = once; diff --git a/function/partial.js b/function/partial.js index 2b72559a8..fb1d04fb6 100644 --- a/function/partial.js +++ b/function/partial.js @@ -11,7 +11,7 @@ var PARTIAL_FLAG = 32; * 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 5f45005fc..634e6a4c4 100644 --- a/function/partialRight.js +++ b/function/partialRight.js @@ -10,7 +10,7 @@ var PARTIAL_RIGHT_FLAG = 64; * 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 bc9ec237b..3a1c15707 100644 --- a/function/restParam.js +++ b/function/restParam.js @@ -30,7 +30,7 @@ function restParam(func, start) { 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/index.js b/index.js index 6e8bd2f0e..546d82c06 100644 --- a/index.js +++ b/index.js @@ -1,9 +1,9 @@ /** * @license - * lodash 3.6.0 (Custom Build) + * lodash 3.7.0 (Custom Build) * Build: `lodash modern -d -o ./index.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; @@ -292,10 +296,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; } } @@ -438,7 +442,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. * @@ -715,9 +719,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; @@ -734,7 +735,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.*?') + '$' ); @@ -745,8 +746,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, @@ -766,6 +769,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, @@ -843,8 +862,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`, @@ -858,15 +877,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. @@ -881,8 +900,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 * @@ -942,6 +961,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` @@ -979,8 +1004,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 @@ -990,7 +1015,7 @@ } catch(e) { support.nonEnumArgs = true; } - }(0, 0)); + }(1, 0)); /** * By default, the template delimiters used by lodash are like those in @@ -1237,7 +1262,7 @@ } /** - * Adds `value` to `key` of the cache. + * Sets `value` to `key` of the cache. * * @private * @name set @@ -1570,13 +1595,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 @@ -1587,26 +1612,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; @@ -1616,7 +1641,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; } } @@ -1624,12 +1649,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) { @@ -1642,7 +1682,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]; @@ -1652,19 +1691,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; @@ -1688,7 +1725,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); } @@ -1698,9 +1735,9 @@ if (type == 'object') { return baseMatches(func); } - return typeof thisArg == 'undefined' - ? baseProperty(func + '') - : baseMatchesProperty(func + '', thisArg); + return thisArg === undefined + ? property(func) + : baseMatchesProperty(func, thisArg); } /** @@ -1722,7 +1759,7 @@ if (customizer) { result = object ? customizer(value, key, object) : customizer(value); } - if (typeof result != 'undefined') { + if (result !== undefined) { return result; } if (!isObject(value)) { @@ -1741,7 +1778,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] @@ -1912,7 +1949,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; } @@ -2009,7 +2046,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 @@ -2095,6 +2132,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. @@ -2163,27 +2226,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. @@ -2240,10 +2299,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); } } @@ -2264,9 +2323,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; } @@ -2291,8 +2353,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))); }; } } @@ -2310,23 +2374,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); }; } @@ -2340,29 +2418,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; @@ -2395,14 +2483,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) @@ -2427,7 +2515,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. @@ -2439,6 +2527,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. @@ -2505,7 +2629,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; } @@ -2564,23 +2688,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) { @@ -2660,7 +2780,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. @@ -2777,7 +2897,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), @@ -2787,7 +2907,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); } @@ -2814,7 +2934,7 @@ if (typeof func != 'function') { return identity; } - if (typeof thisArg == 'undefined') { + if (thisArg === undefined) { return func; } switch (argCount) { @@ -2974,38 +3094,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; - }; + }); } /** @@ -3018,7 +3132,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); } @@ -3295,7 +3409,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)); }; @@ -3310,7 +3424,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); @@ -3326,7 +3440,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); @@ -3373,7 +3487,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); }; @@ -3642,7 +3756,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; @@ -3741,7 +3855,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); } @@ -3866,6 +3980,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. * @@ -3934,7 +4071,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. @@ -3968,6 +4104,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. * @@ -3997,7 +4152,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; @@ -4009,6 +4164,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. * @@ -4118,7 +4293,7 @@ /** * A specialized version of `_.pick` that picks `object` properties specified - * by the `props` array. + * by `props`. * * @private * @param {Object} object The source object. @@ -4244,7 +4419,7 @@ baseForIn(value, function(subValue, key) { result = key; }); - return typeof result == 'undefined' || hasOwnProperty.call(value, result); + return result === undefined || hasOwnProperty.call(value, result); } /** @@ -4252,7 +4427,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) { @@ -4287,7 +4462,7 @@ if (value == null) { return []; } - if (!isLength(value.length)) { + if (!isLength(getLength(value))) { return values(value); } return isObject(value) ? value : Object(value); @@ -4304,6 +4479,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`. * @@ -4888,7 +5081,8 @@ argsLength = arguments.length, caches = [], indexOf = getIndexOf(), - isCommon = indexOf == baseIndexOf; + isCommon = indexOf == baseIndexOf, + result = []; while (++argsIndex < argsLength) { var value = arguments[argsIndex]; @@ -4898,10 +5092,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: @@ -5069,17 +5265,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; }); @@ -5123,19 +5310,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; } @@ -5160,7 +5351,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 @@ -5459,12 +5650,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. @@ -5492,8 +5684,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); @@ -5943,7 +6135,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); } @@ -6048,7 +6240,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); @@ -6218,10 +6410,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. * @@ -6351,7 +6543,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; @@ -6420,16 +6612,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. @@ -6441,15 +6633,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; }); @@ -6486,7 +6679,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 @@ -6580,13 +6772,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 * @@ -6602,8 +6794,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)); } /** @@ -6631,8 +6823,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 * @@ -6804,7 +6996,7 @@ * // => 7 */ function size(collection) { - var length = collection ? collection.length : 0; + var length = collection ? getLength(collection) : 0; return isLength(length) ? length : keys(collection).length; } @@ -6862,7 +7054,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); @@ -6890,9 +7082,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 @@ -6921,104 +7112,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); } /** @@ -7171,7 +7370,8 @@ return function() { if (--n > 0) { result = func.apply(this, arguments); - } else { + } + if (n <= 1) { func = null; } return result; @@ -7186,7 +7386,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 @@ -7228,7 +7428,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 _ @@ -7269,7 +7469,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 @@ -7326,7 +7526,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 _ @@ -7365,7 +7565,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 _ @@ -7777,7 +7977,7 @@ * // `initialize` invokes `createApplication` once */ function once(func) { - return before(func, 2); + return before(2, func); } /** @@ -7788,7 +7988,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 @@ -7821,7 +8021,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 @@ -7905,7 +8105,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, @@ -8309,7 +8509,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; @@ -8335,7 +8535,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 @@ -8366,7 +8566,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; } /** @@ -8488,7 +8688,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 @@ -8521,12 +8721,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), @@ -8536,7 +8737,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); } /** @@ -8591,9 +8792,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); } /** @@ -8761,7 +8962,7 @@ * // => false */ function isUndefined(value) { - return typeof value == 'undefined'; + return value === undefined; } /** @@ -8780,7 +8981,7 @@ * // => [2, 3] */ function toArray(value) { - var length = value ? value.length : 0; + var length = value ? getLength(value) : 0; if (!isLength(length)) { return values(value); } @@ -8826,13 +9027,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 @@ -8842,13 +9047,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 @@ -8889,7 +9098,7 @@ if (guard && isIterateeCall(prototype, properties, guard)) { properties = null; } - return properties ? baseCopy(properties, result, keys(properties)) : result; + return properties ? baseAssign(result, properties) : result; } /** @@ -8897,6 +9106,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 @@ -9020,7 +9231,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 @@ -9076,7 +9287,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 @@ -9149,24 +9360,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; } /** @@ -9229,7 +9484,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 * @@ -9252,7 +9507,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) : []; @@ -9266,7 +9521,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 * @@ -9374,7 +9629,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 @@ -9459,7 +9714,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 * @@ -9515,41 +9770,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; } /** @@ -9557,7 +9864,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 @@ -9700,7 +10007,7 @@ } else { end = +end || 0; } - return value >= start && value < end; + return value >= nativeMin(start, end) && value < nativeMax(start, end); } /** @@ -9825,7 +10132,7 @@ */ function deburr(string) { string = baseToString(string); - return string && string.replace(reLatin1, deburrLetter).replace(reComboMarks, ''); + return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } /** @@ -9854,7 +10161,7 @@ target = (target + ''); var length = string.length; - position = typeof position == 'undefined' + position = position === undefined ? length : nativeMin(position < 0 ? 0 : (+position || 0), length); @@ -9876,9 +10183,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. @@ -10072,7 +10380,7 @@ radix = +radix; } string = trim(string); - return nativeParseInt(string, radix || (reHexPrefix.test(string) ? 16 : 10)); + return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); }; } @@ -10297,9 +10605,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); @@ -10703,9 +11011,7 @@ if (guard && isIterateeCall(func, thisArg, guard)) { thisArg = null; } - return isObjectLike(func) - ? matches(func) - : baseCallback(func, thisArg); + return baseCallback(func, thisArg); } /** @@ -10779,7 +11085,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, @@ -10789,7 +11095,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 @@ -10802,22 +11108,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 @@ -10934,61 +11293,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 @@ -11064,7 +11423,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); @@ -11072,7 +11431,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)`. @@ -11131,7 +11490,7 @@ * // => 10 */ function add(augend, addend) { - return augend + addend; + return (+augend || 0) + (+addend || 0); } /** @@ -11357,6 +11716,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; @@ -11377,6 +11738,7 @@ lodash.remove = remove; lodash.rest = rest; lodash.restParam = restParam; + lodash.set = set; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; @@ -11445,6 +11807,7 @@ lodash.findLastKey = findLastKey; lodash.findWhere = findWhere; lodash.first = first; + lodash.get = get; lodash.has = has; lodash.identity = identity; lodash.includes = includes; @@ -11633,7 +11996,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)); @@ -11655,7 +12018,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); } @@ -11686,7 +12049,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/internal/assignDefaults.js b/internal/assignDefaults.js index 6777ed6da..affd993ad 100644 --- a/internal/assignDefaults.js +++ b/internal/assignDefaults.js @@ -7,7 +7,7 @@ * @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; } module.exports = assignDefaults; diff --git a/internal/assignOwnDefaults.js b/internal/assignOwnDefaults.js index 15b0fffaa..682c460d7 100644 --- a/internal/assignOwnDefaults.js +++ b/internal/assignOwnDefaults.js @@ -7,7 +7,7 @@ var hasOwnProperty = objectProto.hasOwnProperty; /** * 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 @@ -18,7 +18,7 @@ var hasOwnProperty = objectProto.hasOwnProperty; * @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..c5a629d02 --- /dev/null +++ b/internal/assignWith.js @@ -0,0 +1,41 @@ +var getSymbols = require('./getSymbols'), + keys = require('../object/keys'); + +/** 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; +} + +module.exports = assignWith; diff --git a/internal/baseAssign.js b/internal/baseAssign.js index 53532d8d5..8e25f5543 100644 --- a/internal/baseAssign.js +++ b/internal/baseAssign.js @@ -1,35 +1,40 @@ var baseCopy = require('./baseCopy'), + getSymbols = require('./getSymbols'), + isNative = require('../lang/isNative'), keys = require('../object/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)); +}; module.exports = baseAssign; diff --git a/internal/baseAt.js b/internal/baseAt.js index 51015f8f7..f4379897a 100644 --- a/internal/baseAt.js +++ b/internal/baseAt.js @@ -2,12 +2,12 @@ var isIndex = require('./isIndex'), isLength = require('./isLength'); /** - * 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) { @@ -20,7 +20,6 @@ function baseAt(collection, props) { 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 ebbefd8ce..67fe087c4 100644 --- a/internal/baseCallback.js +++ b/internal/baseCallback.js @@ -1,8 +1,8 @@ var baseMatches = require('./baseMatches'), baseMatchesProperty = require('./baseMatchesProperty'), - baseProperty = require('./baseProperty'), bindCallback = require('./bindCallback'), - identity = require('../utility/identity'); + identity = require('../utility/identity'), + property = require('../utility/property'); /** * The base implementation of `_.callback` which supports specifying the @@ -17,7 +17,7 @@ var baseMatches = require('./baseMatches'), function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { - return typeof thisArg == 'undefined' + return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } @@ -27,9 +27,9 @@ function baseCallback(func, thisArg, argCount) { if (type == 'object') { return baseMatches(func); } - return typeof thisArg == 'undefined' - ? baseProperty(func + '') - : baseMatchesProperty(func + '', thisArg); + return thisArg === undefined + ? property(func) + : baseMatchesProperty(func, thisArg); } module.exports = baseCallback; diff --git a/internal/baseClone.js b/internal/baseClone.js index e83e202ca..a747e85b2 100644 --- a/internal/baseClone.js +++ b/internal/baseClone.js @@ -1,13 +1,12 @@ var arrayCopy = require('./arrayCopy'), arrayEach = require('./arrayEach'), - baseCopy = require('./baseCopy'), + baseAssign = require('./baseAssign'), baseForOwn = require('./baseForOwn'), initCloneArray = require('./initCloneArray'), initCloneByTag = require('./initCloneByTag'), initCloneObject = require('./initCloneObject'), isArray = require('../lang/isArray'), - isObject = require('../lang/isObject'), - keys = require('../object/keys'); + isObject = require('../lang/isObject'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', @@ -78,7 +77,7 @@ function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { if (customizer) { result = object ? customizer(value, key, object) : customizer(value); } - if (typeof result != 'undefined') { + if (result !== undefined) { return result; } if (!isObject(value)) { @@ -97,7 +96,7 @@ function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { 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 3f0ebfb94..f2b7657fb 100644 --- a/internal/baseCompareAscending.js +++ b/internal/baseCompareAscending.js @@ -12,10 +12,10 @@ function baseCompareAscending(value, other) { 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 6d713a608..15059f312 100644 --- a/internal/baseCopy.js +++ b/internal/baseCopy.js @@ -1,17 +1,15 @@ /** - * 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 26621d808..ef1a2fa16 100644 --- a/internal/baseFill.js +++ b/internal/baseFill.js @@ -15,7 +15,7 @@ function baseFill(array, value, start, end) { 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 dc9b91c7d..94ee03f92 100644 --- a/internal/baseFor.js +++ b/internal/baseFor.js @@ -3,7 +3,7 @@ var createBaseFor = require('./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..2444eebae --- /dev/null +++ b/internal/baseGet.js @@ -0,0 +1,29 @@ +var toObject = require('./toObject'); + +/** + * 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; +} + +module.exports = baseGet; diff --git a/internal/baseIsEqualDeep.js b/internal/baseIsEqualDeep.js index 3e18d195e..e6829a931 100644 --- a/internal/baseIsEqualDeep.js +++ b/internal/baseIsEqualDeep.js @@ -7,7 +7,6 @@ var equalArrays = require('./equalArrays'), /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', - funcTag = '[object Function]', objectTag = '[object Object]'; /** Used for native method references. */ @@ -59,27 +58,23 @@ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, 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 54a1ccbae..5c9fb3a68 100644 --- a/internal/baseIsMatch.js +++ b/internal/baseIsMatch.js @@ -32,10 +32,10 @@ function baseIsMatch(object, props, values, strictCompareFlags, customizer) { 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 232b2565e..29b40c2e9 100644 --- a/internal/baseMap.js +++ b/internal/baseMap.js @@ -1,4 +1,6 @@ -var baseEach = require('./baseEach'); +var baseEach = require('./baseEach'), + getLength = require('./getLength'), + isLength = require('./isLength'); /** * The base implementation of `_.map` without support for callback shorthands @@ -10,9 +12,12 @@ var baseEach = require('./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 7f07c7dd3..885e9f791 100644 --- a/internal/baseMatches.js +++ b/internal/baseMatches.js @@ -24,8 +24,10 @@ function baseMatches(source) { 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 60b672f1d..1bbd3464d 100644 --- a/internal/baseMatchesProperty.js +++ b/internal/baseMatchesProperty.js @@ -1,25 +1,45 @@ -var baseIsEqual = require('./baseIsEqual'), +var baseGet = require('./baseGet'), + baseIsEqual = require('./baseIsEqual'), + baseSlice = require('./baseSlice'), + isArray = require('../lang/isArray'), + isKey = require('./isKey'), isStrictComparable = require('./isStrictComparable'), - toObject = require('./toObject'); + last = require('../array/last'), + toObject = require('./toObject'), + toPath = require('./toPath'); /** - * 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 b37e78495..f12e7371e 100644 --- a/internal/baseMerge.js +++ b/internal/baseMerge.js @@ -1,11 +1,18 @@ var arrayEach = require('./arrayEach'), - baseForOwn = require('./baseForOwn'), baseMergeDeep = require('./baseMergeDeep'), + getSymbols = require('./getSymbols'), isArray = require('../lang/isArray'), isLength = require('./isLength'), isObject = require('../lang/isObject'), isObjectLike = require('./isObjectLike'), - isTypedArray = require('../lang/isTypedArray'); + isTypedArray = require('../lang/isTypedArray'), + keys = require('../object/keys'); + +/** 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, @@ -17,29 +24,39 @@ var arrayEach = require('./arrayEach'), * @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 f40c4fe56..e734cb27c 100644 --- a/internal/baseMergeDeep.js +++ b/internal/baseMergeDeep.js @@ -1,4 +1,5 @@ var arrayCopy = require('./arrayCopy'), + getLength = require('./getLength'), isArguments = require('../lang/isArguments'), isArray = require('../lang/isArray'), isLength = require('./isLength'), @@ -33,14 +34,14 @@ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stack } 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 50d2043fb..e515941c1 100644 --- a/internal/baseProperty.js +++ b/internal/baseProperty.js @@ -1,5 +1,5 @@ /** - * 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..1b6ce40a1 --- /dev/null +++ b/internal/basePropertyDeep.js @@ -0,0 +1,19 @@ +var baseGet = require('./baseGet'), + toPath = require('./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); + }; +} + +module.exports = basePropertyDeep; diff --git a/internal/basePullAt.js b/internal/basePullAt.js new file mode 100644 index 000000000..cdb3c581e --- /dev/null +++ b/internal/basePullAt.js @@ -0,0 +1,30 @@ +var isIndex = require('./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; +} + +module.exports = basePullAt; diff --git a/internal/baseSlice.js b/internal/baseSlice.js index dc42be0cc..9d1012efa 100644 --- a/internal/baseSlice.js +++ b/internal/baseSlice.js @@ -15,7 +15,7 @@ function baseSlice(array, start, end) { 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 93bc2f25d..0a9ef2079 100644 --- a/internal/baseSortByOrder.js +++ b/internal/baseSortByOrder.js @@ -1,30 +1,26 @@ -var baseEach = require('./baseEach'), +var arrayMap = require('./arrayMap'), + baseCallback = require('./baseCallback'), + baseMap = require('./baseMap'), baseSortBy = require('./baseSortBy'), - compareMultiple = require('./compareMultiple'), - isLength = require('./isLength'); + compareMultiple = require('./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 7259a0844..e8d3ac72f 100644 --- a/internal/baseValues.js +++ b/internal/baseValues.js @@ -1,7 +1,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. diff --git a/internal/binaryIndexBy.js b/internal/binaryIndexBy.js index bac9472d7..fc627b633 100644 --- a/internal/binaryIndexBy.js +++ b/internal/binaryIndexBy.js @@ -27,7 +27,7 @@ function binaryIndexBy(array, value, iteratee, retHighest) { 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), @@ -37,7 +37,7 @@ function binaryIndexBy(array, value, iteratee, retHighest) { 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 aff3c61cf..cdc7f49ae 100644 --- a/internal/bindCallback.js +++ b/internal/bindCallback.js @@ -14,7 +14,7 @@ function bindCallback(func, thisArg, argCount) { 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 da8f01743..cc6c86c03 100644 --- a/internal/compareMultiple.js +++ b/internal/compareMultiple.js @@ -4,7 +4,7 @@ var baseCompareAscending = require('./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 79b02ebd8..43593f06d 100644 --- a/internal/createAssigner.js +++ b/internal/createAssigner.js @@ -1,5 +1,6 @@ var bindCallback = require('./bindCallback'), - isIterateeCall = require('./isIterateeCall'); + isIterateeCall = require('./isIterateeCall'), + restParam = require('../function/restParam'); /** * Creates a function that assigns properties of source object(s) to a given @@ -12,38 +13,32 @@ var bindCallback = require('./bindCallback'), * @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; - }; + }); } module.exports = createAssigner; diff --git a/internal/createBaseEach.js b/internal/createBaseEach.js index 5f9f2bf84..b55c39ba1 100644 --- a/internal/createBaseEach.js +++ b/internal/createBaseEach.js @@ -1,4 +1,5 @@ -var isLength = require('./isLength'), +var getLength = require('./getLength'), + isLength = require('./isLength'), toObject = require('./toObject'); /** @@ -11,7 +12,7 @@ var isLength = require('./isLength'), */ 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 b0d1659b3..2aad11c5f 100644 --- a/internal/createForEach.js +++ b/internal/createForEach.js @@ -11,7 +11,7 @@ var bindCallback = require('./bindCallback'), */ 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 7d7933b5a..f63ffa0ba 100644 --- a/internal/createForIn.js +++ b/internal/createForIn.js @@ -10,7 +10,7 @@ var bindCallback = require('./bindCallback'), */ 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 6690972e4..b9a83c3b5 100644 --- a/internal/createForOwn.js +++ b/internal/createForOwn.js @@ -9,7 +9,7 @@ var bindCallback = require('./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 3633a6f71..816f4ce71 100644 --- a/internal/createReduce.js +++ b/internal/createReduce.js @@ -13,7 +13,7 @@ var baseCallback = require('./baseCallback'), 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 c3bae1b23..0b032ac6a 100644 --- a/internal/equalArrays.js +++ b/internal/equalArrays.js @@ -32,7 +32,7 @@ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stack ? 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 6c4110a6f..5ea4ec5b8 100644 --- a/internal/equalObjects.js +++ b/internal/equalObjects.js @@ -46,7 +46,7 @@ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, sta ? 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..00a8622bf --- /dev/null +++ b/internal/getLength.js @@ -0,0 +1,15 @@ +var baseProperty = require('./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'); + +module.exports = getLength; diff --git a/internal/getSymbols.js b/internal/getSymbols.js new file mode 100644 index 000000000..e6a4d2991 --- /dev/null +++ b/internal/getSymbols.js @@ -0,0 +1,19 @@ +var constant = require('../utility/constant'), + isNative = require('../lang/isNative'), + toObject = require('./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)); +}; + +module.exports = getSymbols; diff --git a/internal/initCloneByTag.js b/internal/initCloneByTag.js index 25cb426bd..8e3afc63f 100644 --- a/internal/initCloneByTag.js +++ b/internal/initCloneByTag.js @@ -27,7 +27,6 @@ var reFlags = /\w*$/; * **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..935110fd1 --- /dev/null +++ b/internal/invokePath.js @@ -0,0 +1,26 @@ +var baseGet = require('./baseGet'), + baseSlice = require('./baseSlice'), + isKey = require('./isKey'), + last = require('../array/last'), + toPath = require('./toPath'); + +/** + * 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); +} + +module.exports = invokePath; diff --git a/internal/isIterateeCall.js b/internal/isIterateeCall.js index 59b901ce7..5adfd95d4 100644 --- a/internal/isIterateeCall.js +++ b/internal/isIterateeCall.js @@ -1,4 +1,5 @@ -var isIndex = require('./isIndex'), +var getLength = require('./getLength'), + isIndex = require('./isIndex'), isLength = require('./isLength'), isObject = require('../lang/isObject'); @@ -17,7 +18,7 @@ function isIterateeCall(value, index, object) { } 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..10005cc97 --- /dev/null +++ b/internal/isKey.js @@ -0,0 +1,28 @@ +var isArray = require('../lang/isArray'), + toObject = require('./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)); +} + +module.exports = isKey; diff --git a/internal/mapSet.js b/internal/mapSet.js index df7b19158..0434c3f30 100644 --- a/internal/mapSet.js +++ b/internal/mapSet.js @@ -1,5 +1,5 @@ /** - * 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 cfeac8800..cd1e3b87a 100644 --- a/internal/pickByArray.js +++ b/internal/pickByArray.js @@ -2,7 +2,7 @@ var toObject = require('./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/shimIsPlainObject.js b/internal/shimIsPlainObject.js index 3e75ce49a..9821286d6 100644 --- a/internal/shimIsPlainObject.js +++ b/internal/shimIsPlainObject.js @@ -44,7 +44,7 @@ function shimIsPlainObject(value) { baseForIn(value, function(subValue, key) { result = key; }); - return typeof result == 'undefined' || hasOwnProperty.call(value, result); + return result === undefined || hasOwnProperty.call(value, result); } module.exports = shimIsPlainObject; diff --git a/internal/shimKeys.js b/internal/shimKeys.js index 282b11058..d165c40cb 100644 --- a/internal/shimKeys.js +++ b/internal/shimKeys.js @@ -16,7 +16,7 @@ var hasOwnProperty = objectProto.hasOwnProperty; * 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 7000818fb..3999a1496 100644 --- a/internal/toIterable.js +++ b/internal/toIterable.js @@ -1,4 +1,5 @@ -var isLength = require('./isLength'), +var getLength = require('./getLength'), + isLength = require('./isLength'), isObject = require('../lang/isObject'), values = require('../object/values'); @@ -13,7 +14,7 @@ function toIterable(value) { 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..45314d1c4 --- /dev/null +++ b/internal/toPath.js @@ -0,0 +1,28 @@ +var baseToString = require('./baseToString'), + isArray = require('../lang/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; +} + +module.exports = toPath; diff --git a/lang/isEmpty.js b/lang/isEmpty.js index bdba5b60c..7a6f6f24f 100644 --- a/lang/isEmpty.js +++ b/lang/isEmpty.js @@ -1,4 +1,5 @@ -var isArguments = require('./isArguments'), +var getLength = require('../internal/getLength'), + isArguments = require('./isArguments'), isArray = require('./isArray'), isFunction = require('./isFunction'), isLength = require('../internal/isLength'), @@ -37,7 +38,7 @@ function isEmpty(value) { 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 691eecc6b..7daddb858 100644 --- a/lang/isEqual.js +++ b/lang/isEqual.js @@ -20,7 +20,7 @@ var baseIsEqual = require('../internal/baseIsEqual'), * @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 @@ -51,7 +51,7 @@ function isEqual(value, other, customizer, thisArg) { 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; } module.exports = isEqual; diff --git a/lang/isMatch.js b/lang/isMatch.js index bd6576b03..9bc7ac174 100644 --- a/lang/isMatch.js +++ b/lang/isMatch.js @@ -21,7 +21,7 @@ var baseIsMatch = require('../internal/baseIsMatch'), * @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 @@ -54,12 +54,13 @@ function isMatch(object, source, customizer, thisArg) { 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), @@ -69,7 +70,7 @@ function isMatch(object, source, customizer, thisArg) { 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); } module.exports = isMatch; diff --git a/lang/isNative.js b/lang/isNative.js index 25229e2ba..f27bb5a70 100644 --- a/lang/isNative.js +++ b/lang/isNative.js @@ -5,7 +5,7 @@ var escapeRegExp = require('../string/escapeRegExp'), 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; @@ -20,7 +20,7 @@ var fnToString = Function.prototype.toString; 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.*?') + '$' ); @@ -46,9 +46,9 @@ function isNative(value) { 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); } module.exports = isNative; diff --git a/lang/isUndefined.js b/lang/isUndefined.js index b3d237b76..d64e560c6 100644 --- a/lang/isUndefined.js +++ b/lang/isUndefined.js @@ -15,7 +15,7 @@ * // => false */ function isUndefined(value) { - return typeof value == 'undefined'; + return value === undefined; } module.exports = isUndefined; diff --git a/lang/toArray.js b/lang/toArray.js index 271833c61..72b0b46e1 100644 --- a/lang/toArray.js +++ b/lang/toArray.js @@ -1,4 +1,5 @@ var arrayCopy = require('../internal/arrayCopy'), + getLength = require('../internal/getLength'), isLength = require('../internal/isLength'), values = require('../object/values'); @@ -18,7 +19,7 @@ var arrayCopy = require('../internal/arrayCopy'), * // => [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/math/add.js b/math/add.js index 03e5a143a..59ced2fb6 100644 --- a/math/add.js +++ b/math/add.js @@ -13,7 +13,7 @@ * // => 10 */ function add(augend, addend) { - return augend + addend; + return (+augend || 0) + (+addend || 0); } module.exports = add; diff --git a/number/inRange.js b/number/inRange.js index d599a49cd..4e5cc88b0 100644 --- a/number/inRange.js +++ b/number/inRange.js @@ -1,3 +1,7 @@ +/* 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`. @@ -37,7 +41,7 @@ function inRange(value, start, end) { } else { end = +end || 0; } - return value >= start && value < end; + return value >= nativeMin(start, end) && value < nativeMax(start, end); } module.exports = inRange; diff --git a/object.js b/object.js index 6421b66bd..2d7a5c65b 100644 --- a/object.js +++ b/object.js @@ -10,6 +10,7 @@ module.exports = { 'forOwn': require('./object/forOwn'), 'forOwnRight': require('./object/forOwnRight'), 'functions': require('./object/functions'), + 'get': require('./object/get'), 'has': require('./object/has'), 'invert': require('./object/invert'), 'keys': require('./object/keys'), @@ -21,6 +22,7 @@ module.exports = { 'pairs': require('./object/pairs'), 'pick': require('./object/pick'), 'result': require('./object/result'), + 'set': require('./object/set'), 'transform': require('./object/transform'), 'values': require('./object/values'), 'valuesIn': require('./object/valuesIn') diff --git a/object/assign.js b/object/assign.js index 0914c4517..3c6770e94 100644 --- a/object/assign.js +++ b/object/assign.js @@ -1,4 +1,5 @@ -var baseAssign = require('../internal/baseAssign'), +var assignWith = require('../internal/assignWith'), + baseAssign = require('../internal/baseAssign'), createAssigner = require('../internal/createAssigner'); /** @@ -8,13 +9,17 @@ var baseAssign = require('../internal/baseAssign'), * 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 @@ -24,12 +29,16 @@ var baseAssign = require('../internal/baseAssign'), * * // 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); +}); module.exports = assign; diff --git a/object/create.js b/object/create.js index afb4df7c9..a11d75be6 100644 --- a/object/create.js +++ b/object/create.js @@ -1,7 +1,6 @@ -var baseCopy = require('../internal/baseCopy'), +var baseAssign = require('../internal/baseAssign'), baseCreate = require('../internal/baseCreate'), - isIterateeCall = require('../internal/isIterateeCall'), - keys = require('./keys'); + isIterateeCall = require('../internal/isIterateeCall'); /** * Creates an object that inherits from the given `prototype` object. If a @@ -42,7 +41,7 @@ function create(prototype, properties, guard) { if (guard && isIterateeCall(prototype, properties, guard)) { properties = null; } - return properties ? baseCopy(properties, result, keys(properties)) : result; + return properties ? baseAssign(result, properties) : result; } module.exports = create; diff --git a/object/defaults.js b/object/defaults.js index b4efe02a9..bcbd9f46b 100644 --- a/object/defaults.js +++ b/object/defaults.js @@ -7,6 +7,8 @@ var assign = require('./assign'), * 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 afb58f291..52d34af8e 100644 --- a/object/forIn.js +++ b/object/forIn.js @@ -4,7 +4,7 @@ var baseFor = require('../internal/baseFor'), /** * 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 3d5cfcac5..747bb7651 100644 --- a/object/forOwn.js +++ b/object/forOwn.js @@ -4,7 +4,7 @@ var baseForOwn = require('../internal/baseForOwn'), /** * 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..7e8a3103b --- /dev/null +++ b/object/get.js @@ -0,0 +1,33 @@ +var baseGet = require('../internal/baseGet'), + toPath = require('../internal/toPath'); + +/** + * 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; +} + +module.exports = get; diff --git a/object/has.js b/object/has.js index 50eaa7ef3..f208f8a01 100644 --- a/object/has.js +++ b/object/has.js @@ -1,3 +1,9 @@ +var baseGet = require('../internal/baseGet'), + baseSlice = require('../internal/baseSlice'), + isKey = require('../internal/isKey'), + last = require('../array/last'), + toPath = require('../internal/toPath'); + /** Used for native method references. */ var objectProto = Object.prototype; @@ -5,24 +11,39 @@ var objectProto = Object.prototype; 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; } module.exports = has; diff --git a/object/keys.js b/object/keys.js index 2fa42707e..c02865675 100644 --- a/object/keys.js +++ b/object/keys.js @@ -16,7 +16,7 @@ var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys; * @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 * @@ -39,7 +39,7 @@ var keys = !nativeKeys ? shimKeys : function(object) { 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 5a88e12ca..72a1c5e26 100644 --- a/object/keysIn.js +++ b/object/keysIn.js @@ -19,7 +19,7 @@ var hasOwnProperty = objectProto.hasOwnProperty; * @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 5f8d3a0a6..dc0b95eff 100644 --- a/object/merge.js +++ b/object/merge.js @@ -15,7 +15,7 @@ var baseMerge = require('../internal/baseMerge'), * @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 9a58fb66e..64de3edbe 100644 --- a/object/pairs.js +++ b/object/pairs.js @@ -7,7 +7,7 @@ var keys = require('./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 7e5345571..05ca6df66 100644 --- a/object/result.js +++ b/object/result.js @@ -1,41 +1,49 @@ -var isFunction = require('../lang/isFunction'); +var baseGet = require('../internal/baseGet'), + baseSlice = require('../internal/baseSlice'), + isFunction = require('../lang/isFunction'), + isKey = require('../internal/isKey'), + last = require('../array/last'), + toPath = require('../internal/toPath'); /** - * 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; } module.exports = result; diff --git a/object/set.js b/object/set.js new file mode 100644 index 000000000..02caf318d --- /dev/null +++ b/object/set.js @@ -0,0 +1,55 @@ +var isIndex = require('../internal/isIndex'), + isKey = require('../internal/isKey'), + isObject = require('../lang/isObject'), + toPath = require('../internal/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; +} + +module.exports = set; diff --git a/object/transform.js b/object/transform.js index 7686c9a80..4537ba1a0 100644 --- a/object/transform.js +++ b/object/transform.js @@ -12,7 +12,7 @@ var arrayEach = require('../internal/arrayEach'), * `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 a4d47e984..8705a4a03 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lodash", - "version": "3.6.0", + "version": "3.7.0", "description": "The modern build of lodash modular utilities.", "homepage": "https://lodash.com/", "icon": "https://lodash.com/icon.svg", diff --git a/string/deburr.js b/string/deburr.js index 30abcffd5..0bd03e62d 100644 --- a/string/deburr.js +++ b/string/deburr.js @@ -1,10 +1,8 @@ var baseToString = require('../internal/baseToString'), deburrLetter = require('../internal/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; @@ -25,7 +23,7 @@ var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; */ function deburr(string) { string = baseToString(string); - return string && string.replace(reLatin1, deburrLetter).replace(reComboMarks, ''); + return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } module.exports = deburr; diff --git a/string/endsWith.js b/string/endsWith.js index aa74b9e63..26821e266 100644 --- a/string/endsWith.js +++ b/string/endsWith.js @@ -29,7 +29,7 @@ function endsWith(string, target, position) { 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 057a2061c..c4e72cc08 100644 --- a/string/escape.js +++ b/string/escape.js @@ -19,9 +19,10 @@ var reUnescapedHtml = /[&<>"'`]/g, * (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 519dcdbba..c4cf71a96 100644 --- a/string/parseInt.js +++ b/string/parseInt.js @@ -2,7 +2,7 @@ var isIterateeCall = require('../internal/isIterateeCall'), trim = require('./trim'); /** Used to detect hexadecimal string values. */ -var reHexPrefix = /^0[xX]/; +var reHasHexPrefix = /^0[xX]/; /** Used to detect and test for whitespace. */ var whitespace = ( @@ -60,7 +60,7 @@ if (nativeParseInt(whitespace + '08') != 8) { 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 5ef49a707..b3910481e 100644 --- a/string/template.js +++ b/string/template.js @@ -1,4 +1,5 @@ var assignOwnDefaults = require('../internal/assignOwnDefaults'), + assignWith = require('../internal/assignWith'), attempt = require('../utility/attempt'), baseAssign = require('../internal/baseAssign'), baseToString = require('../internal/baseToString'), @@ -15,9 +16,7 @@ var reEmptyStringLeading = /\b__p \+= '';/g, 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. */ @@ -131,9 +130,9 @@ function template(string, options, otherOptions) { 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 c70322f0d..6db6adb9f 100644 --- a/support.js +++ b/support.js @@ -17,6 +17,12 @@ var propertyIsEnumerable = objectProto.propertyIsEnumerable; 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` @@ -54,8 +60,8 @@ var support = {}; * 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 @@ -65,6 +71,6 @@ var support = {}; } catch(e) { support.nonEnumArgs = true; } -}(0, 0)); +}(1, 0)); module.exports = support; diff --git a/utility.js b/utility.js index 062c92ebd..25311faef 100644 --- a/utility.js +++ b/utility.js @@ -6,6 +6,8 @@ module.exports = { 'iteratee': require('./utility/iteratee'), 'matches': require('./utility/matches'), 'matchesProperty': require('./utility/matchesProperty'), + 'method': require('./utility/method'), + 'methodOf': require('./utility/methodOf'), 'mixin': require('./utility/mixin'), 'noop': require('./utility/noop'), 'property': require('./utility/property'), diff --git a/utility/callback.js b/utility/callback.js index d864d46c5..83d5d88bf 100644 --- a/utility/callback.js +++ b/utility/callback.js @@ -1,7 +1,5 @@ var baseCallback = require('../internal/baseCallback'), - isIterateeCall = require('../internal/isIterateeCall'), - isObjectLike = require('../internal/isObjectLike'), - matches = require('./matches'); + isIterateeCall = require('../internal/isIterateeCall'); /** * Creates a function that invokes `func` with the `this` binding of `thisArg` @@ -45,9 +43,7 @@ function callback(func, thisArg, guard) { if (guard && isIterateeCall(func, thisArg, guard)) { thisArg = null; } - return isObjectLike(func) - ? matches(func) - : baseCallback(func, thisArg); + return baseCallback(func, thisArg); } module.exports = callback; diff --git a/utility/matchesProperty.js b/utility/matchesProperty.js index 89e5e0e9c..05a7efb1c 100644 --- a/utility/matchesProperty.js +++ b/utility/matchesProperty.js @@ -2,7 +2,7 @@ var baseClone = require('../internal/baseClone'), baseMatchesProperty = require('../internal/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, @@ -12,7 +12,7 @@ var baseClone = require('../internal/baseClone'), * @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 @@ -25,8 +25,8 @@ var baseClone = require('../internal/baseClone'), * _.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)); } module.exports = matchesProperty; diff --git a/utility/method.js b/utility/method.js new file mode 100644 index 000000000..c3b8cd58e --- /dev/null +++ b/utility/method.js @@ -0,0 +1,31 @@ +var invokePath = require('../internal/invokePath'), + restParam = require('../function/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); + } +}); + +module.exports = method; diff --git a/utility/methodOf.js b/utility/methodOf.js new file mode 100644 index 000000000..9286cc25f --- /dev/null +++ b/utility/methodOf.js @@ -0,0 +1,30 @@ +var invokePath = require('../internal/invokePath'), + restParam = require('../function/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); + }; +}); + +module.exports = methodOf; diff --git a/utility/mixin.js b/utility/mixin.js index f1a6e5261..926042b74 100644 --- a/utility/mixin.js +++ b/utility/mixin.js @@ -15,13 +15,13 @@ var push = arrayProto.push; * 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 154ca0947..e149f6d10 100644 --- a/utility/property.js +++ b/utility/property.js @@ -1,30 +1,31 @@ -var baseProperty = require('../internal/baseProperty'); +var baseProperty = require('../internal/baseProperty'), + basePropertyDeep = require('../internal/basePropertyDeep'), + isKey = require('../internal/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); } module.exports = property; diff --git a/utility/propertyOf.js b/utility/propertyOf.js index fcd7304ce..a3b9c2799 100644 --- a/utility/propertyOf.js +++ b/utility/propertyOf.js @@ -1,25 +1,29 @@ +var baseGet = require('../internal/baseGet'), + toPath = require('../internal/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 1e40a6054..fad70a42f 100644 --- a/utility/range.js +++ b/utility/range.js @@ -9,7 +9,7 @@ var nativeMax = Math.max; /** * 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 8279a0682..28e6f0263 100644 --- a/utility/times.js +++ b/utility/times.js @@ -1,5 +1,8 @@ var bindCallback = require('../internal/bindCallback'); +/** Native method references. */ +var floor = Math.floor; + /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = global.isFinite, nativeMin = Math.min; @@ -27,7 +30,7 @@ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; * _.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 @@ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; * // => 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)`.