Compare commits

...

10 Commits

Author SHA1 Message Date
John-David Dalton
1d77dfa4b7 Bump to v3.10.1. 2015-08-03 08:35:01 -07:00
jdalton
4bd2890bbd Bump to v3.10.0. 2015-06-30 00:06:56 -07:00
jdalton
6ee2b9a7b8 Bump to v3.9.3. 2015-05-25 16:45:11 -07:00
jdalton
3d3907ff27 Bump to v3.9.2. 2015-05-24 01:42:23 -07:00
jdalton
30daf83737 Bump to v3.9.0. 2015-05-19 08:43:25 -07:00
jdalton
d7b2bedafc Bump to v3.8.0. 2015-05-01 01:02:48 -07:00
jdalton
5eb8db31d7 Bump to v3.7.0. 2015-04-15 20:56:31 -07:00
jdalton
801ffd8adf Bump to v3.6.0. 2015-03-24 22:52:48 -07:00
jdalton
ee1f12c851 Bump to v3.5.0. 2015-03-08 18:09:08 -07:00
jdalton
d01a1e4ef3 Bump to v3.4.0. 2015-03-06 01:11:05 -08:00
332 changed files with 3562 additions and 2417 deletions

View File

@@ -1,5 +1,5 @@
Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
Based on Underscore.js 1.7.0, copyright 2009-2015 Jeremy Ashkenas,
Based on Underscore.js, copyright 2009-2015 Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
Permission is hereby granted, free of charge, to any person obtaining

View File

@@ -1,4 +1,4 @@
# lodash-es v3.3.1
# lodash-es v3.10.1
The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash](https://lodash.com/) exported as [ES](https://people.mozilla.org/~jorendorff/es6-draft.html) modules.
@@ -7,4 +7,4 @@ Generated using [lodash-cli](https://www.npmjs.com/package/lodash-cli):
$ lodash modularize modern exports=es -o ./
```
See the [package source](https://github.com/lodash/lodash/tree/3.3.1-es) for more details.
See the [package source](https://github.com/lodash/lodash/tree/3.10.1-es) for more details.

View File

@@ -34,10 +34,12 @@ import union from './array/union';
import uniq from './array/uniq';
import unique from './array/unique';
import unzip from './array/unzip';
import unzipWith from './array/unzipWith';
import without from './array/without';
import xor from './array/xor';
import zip from './array/zip';
import zipObject from './array/zipObject';
import zipWith from './array/zipWith';
export default {
'chunk': chunk,
@@ -76,8 +78,10 @@ export default {
'uniq': uniq,
'unique': unique,
'unzip': unzip,
'unzipWith': unzipWith,
'without': without,
'xor': xor,
'zip': zip,
'zipObject': zipObject
'zipObject': zipObject,
'zipWith': zipWith
};

View File

@@ -1,11 +1,10 @@
import baseSlice from '../internal/baseSlice';
import isIterateeCall from '../internal/isIterateeCall';
/** Native method references. */
var ceil = Math.ceil;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
var nativeCeil = Math.ceil,
nativeFloor = Math.floor,
nativeMax = Math.max;
/**
* Creates an array of elements split into groups the length of `size`.
@@ -31,12 +30,12 @@ function chunk(array, size, guard) {
if (guard ? isIterateeCall(array, size, guard) : size == null) {
size = 1;
} else {
size = nativeMax(+size || 1, 1);
size = nativeMax(nativeFloor(size) || 1, 1);
}
var index = 0,
length = array ? array.length : 0,
resIndex = -1,
result = Array(ceil(length / size));
result = Array(nativeCeil(length / size));
while (index < length) {
result[++resIndex] = baseSlice(array, index, (index += size));

View File

@@ -1,16 +1,13 @@
import baseDifference from '../internal/baseDifference';
import baseFlatten from '../internal/baseFlatten';
import isArguments from '../lang/isArguments';
import isArray from '../lang/isArray';
import isArrayLike from '../internal/isArrayLike';
import isObjectLike from '../internal/isObjectLike';
import restParam from '../function/restParam';
/**
* Creates an array excluding all values of the provided arrays using
* `SameValueZero` for equality comparisons.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
* Creates an array of unique `array` values not included in the other
* provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
@@ -23,17 +20,10 @@ import isArray from '../lang/isArray';
* _.difference([1, 2, 3], [4, 2]);
* // => [1, 3]
*/
function difference() {
var index = -1,
length = arguments.length;
while (++index < length) {
var value = arguments[index];
if (isArray(value) || isArguments(value)) {
break;
}
}
return baseDifference(value, baseFlatten(arguments, false, true, ++index));
}
var difference = restParam(function(array, values) {
return (isObjectLike(array) && isArrayLike(array))
? baseDifference(array, baseFlatten(values, false, true))
: [];
});
export default difference;

View File

@@ -1,10 +1,10 @@
import baseCallback from '../internal/baseCallback';
import baseSlice from '../internal/baseSlice';
import baseWhile from '../internal/baseWhile';
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* bound to `thisArg` and invoked with three arguments; (value, index, array).
* bound to `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -39,7 +39,7 @@ import baseSlice from '../internal/baseSlice';
* ];
*
* // using the `_.matches` callback shorthand
* _.pluck(_.dropRightWhile(users, { 'user': pebbles, 'active': false }), 'user');
* _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
* // => ['barney', 'fred']
*
* // using the `_.matchesProperty` callback shorthand
@@ -51,13 +51,9 @@ import baseSlice from '../internal/baseSlice';
* // => ['barney', 'fred', 'pebbles']
*/
function dropRightWhile(array, predicate, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
predicate = baseCallback(predicate, thisArg, 3);
while (length-- && predicate(array[length], length, array)) {}
return baseSlice(array, 0, length + 1);
return (array && array.length)
? baseWhile(array, baseCallback(predicate, thisArg, 3), true, true)
: [];
}
export default dropRightWhile;

View File

@@ -1,10 +1,10 @@
import baseCallback from '../internal/baseCallback';
import baseSlice from '../internal/baseSlice';
import baseWhile from '../internal/baseWhile';
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* bound to `thisArg` and invoked with three arguments; (value, index, array).
* bound to `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -51,14 +51,9 @@ import baseSlice from '../internal/baseSlice';
* // => ['barney', 'fred', 'pebbles']
*/
function dropWhile(array, predicate, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
var index = -1;
predicate = baseCallback(predicate, thisArg, 3);
while (++index < length && predicate(array[index], index, array)) {}
return baseSlice(array, index);
return (array && array.length)
? baseWhile(array, baseCallback(predicate, thisArg, 3), true)
: [];
}
export default dropWhile;

View File

@@ -15,6 +15,19 @@ import isIterateeCall from '../internal/isIterateeCall';
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8], '*', 1, 2);
* // => [4, '*', 8]
*/
function fill(array, value, start, end) {
var length = array ? array.length : 0;

View File

@@ -1,8 +1,8 @@
import baseCallback from '../internal/baseCallback';
import createFindIndex from '../internal/createFindIndex';
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for, instead of the element itself.
* element `predicate` returns truthy for instead of the element itself.
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -48,17 +48,6 @@ import baseCallback from '../internal/baseCallback';
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, thisArg) {
var index = -1,
length = array ? array.length : 0;
predicate = baseCallback(predicate, thisArg, 3);
while (++index < length) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
var findIndex = createFindIndex();
export default findIndex;

View File

@@ -1,4 +1,4 @@
import baseCallback from '../internal/baseCallback';
import createFindIndex from '../internal/createFindIndex';
/**
* This method is like `_.findIndex` except that it iterates over elements
@@ -42,21 +42,12 @@ import baseCallback from '../internal/baseCallback';
*
* // using the `_.matchesProperty` callback shorthand
* _.findLastIndex(users, 'active', false);
* // => 1
* // => 2
*
* // using the `_.property` callback shorthand
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, thisArg) {
var length = array ? array.length : 0;
predicate = baseCallback(predicate, thisArg, 3);
while (length--) {
if (predicate(array[length], length, array)) {
return length;
}
}
return -1;
}
var findLastIndex = createFindIndex(true);
export default findLastIndex;

View File

@@ -3,7 +3,7 @@ import isIterateeCall from '../internal/isIterateeCall';
/**
* Flattens a nested array. If `isDeep` is `true` the array is recursively
* flattened, otherwise it is only flattened a single level.
* flattened, otherwise it's only flattened a single level.
*
* @static
* @memberOf _
@@ -15,11 +15,11 @@ import isIterateeCall from '../internal/isIterateeCall';
* @example
*
* _.flatten([1, [2, 3, [4]]]);
* // => [1, 2, 3, [4]];
* // => [1, 2, 3, [4]]
*
* // using `isDeep`
* _.flatten([1, [2, 3, [4]]], true);
* // => [1, 2, 3, 4];
* // => [1, 2, 3, 4]
*/
function flatten(array, isDeep, guard) {
var length = array ? array.length : 0;

View File

@@ -11,7 +11,7 @@ import baseFlatten from '../internal/baseFlatten';
* @example
*
* _.flattenDeep([1, [2, 3, [4]]]);
* // => [1, 2, 3, 4];
* // => [1, 2, 3, 4]
*/
function flattenDeep(array) {
var length = array ? array.length : 0;

View File

@@ -6,14 +6,10 @@ var nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using `SameValueZero` for equality comparisons. If `fromIndex` is negative,
* it is used as the offset from the end of `array`. If `array` is sorted
* providing `true` for `fromIndex` performs a faster binary search.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
* using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the offset
* from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
* performs a faster binary search.
*
* @static
* @memberOf _
@@ -42,14 +38,16 @@ function indexOf(array, value, fromIndex) {
return -1;
}
if (typeof fromIndex == 'number') {
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
} else if (fromIndex) {
var index = binaryIndex(array, value),
other = array[index];
return (value === value ? value === other : other !== other) ? index : -1;
var index = binaryIndex(array, value);
if (index < length &&
(value === value ? (value === array[index]) : (array[index] !== array[index]))) {
return index;
}
return -1;
}
return baseIndexOf(array, value, fromIndex);
return baseIndexOf(array, value, fromIndex || 0);
}
export default indexOf;

View File

@@ -1,18 +1,14 @@
import baseIndexOf from '../internal/baseIndexOf';
import cacheIndexOf from '../internal/cacheIndexOf';
import createCache from '../internal/createCache';
import isArguments from '../lang/isArguments';
import isArray from '../lang/isArray';
import isArrayLike from '../internal/isArrayLike';
import restParam from '../function/restParam';
/**
* Creates an array of unique values in all provided arrays using `SameValueZero`
* Creates an array of unique values that are included in all of the provided
* arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @category Array
@@ -22,36 +18,31 @@ import isArray from '../lang/isArray';
* _.intersection([1, 2], [4, 2], [2, 1]);
* // => [2]
*/
function intersection() {
var args = [],
argsIndex = -1,
argsLength = arguments.length,
caches = [],
var intersection = restParam(function(arrays) {
var othLength = arrays.length,
othIndex = othLength,
caches = Array(length),
indexOf = baseIndexOf,
isCommon = true;
isCommon = true,
result = [];
while (++argsIndex < argsLength) {
var value = arguments[argsIndex];
if (isArray(value) || isArguments(value)) {
args.push(value);
caches.push((isCommon && value.length >= 120) ? createCache(argsIndex && value) : null);
}
while (othIndex--) {
var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
}
argsLength = args.length;
var array = args[0],
var array = arrays[0],
index = -1,
length = array ? array.length : 0,
result = [],
seen = caches[0];
outer:
while (++index < length) {
value = array[index];
if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value)) < 0) {
argsIndex = argsLength;
while (--argsIndex) {
var cache = caches[argsIndex];
if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
var othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
continue outer;
}
}
@@ -62,6 +53,6 @@ function intersection() {
}
}
return result;
}
});
export default intersection;

View File

@@ -41,7 +41,10 @@ function lastIndexOf(array, value, fromIndex) {
} else if (fromIndex) {
index = binaryIndex(array, value, true) - 1;
var other = array[index];
return (value === value ? value === other : other !== other) ? index : -1;
if (value === value ? (value === other) : (other !== other)) {
return index;
}
return -1;
}
if (value !== value) {
return indexOfNaN(array, index, true);

View File

@@ -7,14 +7,11 @@ var arrayProto = Array.prototype;
var splice = arrayProto.splice;
/**
* Removes all provided values from `array` using `SameValueZero` for equality
* comparisons.
* Removes all provided values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Notes:**
* - Unlike `_.without`, this method mutates `array`.
* - `SameValueZero` comparisons are like strict equality comparisons, e.g. `===`,
* except that `NaN` matches `NaN`. See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
* **Note:** Unlike `_.without`, this method mutates `array`.
*
* @static
* @memberOf _
@@ -31,17 +28,19 @@ var splice = arrayProto.splice;
* // => [1, 1]
*/
function pull() {
var array = arguments[0];
var args = arguments,
array = args[0];
if (!(array && array.length)) {
return array;
}
var index = 0,
indexOf = baseIndexOf,
length = arguments.length;
length = args.length;
while (++index < length) {
var fromIndex = 0,
value = arguments[index];
value = args[index];
while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
splice.call(array, fromIndex, 1);

View File

@@ -1,5 +1,8 @@
import baseAt from '../internal/baseAt';
import baseCompareAscending from '../internal/baseCompareAscending';
import baseFlatten from '../internal/baseFlatten';
import basePullAt from '../internal/basePullAt';
import restParam from '../function/restParam';
/**
* Removes elements from `array` corresponding to the given indexes and returns
@@ -26,8 +29,12 @@ import basePullAt from '../internal/basePullAt';
* console.log(evens);
* // => [10, 20]
*/
function pullAt(array) {
return basePullAt(array || [], baseFlatten(arguments, false, false, 1));
}
var pullAt = restParam(function(array, indexes) {
indexes = baseFlatten(indexes);
var result = baseAt(array, indexes);
basePullAt(array, indexes.sort(baseCompareAscending));
return result;
});
export default pullAt;

View File

@@ -1,15 +1,10 @@
import baseCallback from '../internal/baseCallback';
/** Used for native method references. */
var arrayProto = Array.prototype;
/** Native method references. */
var splice = arrayProto.splice;
import basePullAt from '../internal/basePullAt';
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is bound to
* `thisArg` and invoked with three arguments; (value, index, array).
* `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -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;
}

View File

@@ -4,7 +4,7 @@ import isIterateeCall from '../internal/isIterateeCall';
/**
* 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

View File

@@ -1,22 +1,20 @@
import baseCallback from '../internal/baseCallback';
import binaryIndex from '../internal/binaryIndex';
import binaryIndexBy from '../internal/binaryIndexBy';
import createSortedIndex from '../internal/createSortedIndex';
/**
* Uses a binary search to determine the lowest index at which `value` should
* be inserted into `array` in order to maintain its sort order. If an iteratee
* function is provided it is invoked for `value` and each element of `array`
* function is provided it's invoked for `value` and each element of `array`
* to compute their sort ranking. The iteratee is bound to `thisArg` and
* invoked with one argument; (value).
*
* If a property name is provided for `predicate` the created `_.property`
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
@@ -50,10 +48,6 @@ import binaryIndexBy from '../internal/binaryIndexBy';
* _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
* // => 1
*/
function sortedIndex(array, value, iteratee, thisArg) {
return iteratee == null
? binaryIndex(array, value)
: binaryIndexBy(array, value, baseCallback(iteratee, thisArg, 1));
}
var sortedIndex = createSortedIndex();
export default sortedIndex;

View File

@@ -1,6 +1,4 @@
import baseCallback from '../internal/baseCallback';
import binaryIndex from '../internal/binaryIndex';
import binaryIndexBy from '../internal/binaryIndexBy';
import createSortedIndex from '../internal/createSortedIndex';
/**
* This method is like `_.sortedIndex` except that it returns the highest
@@ -22,10 +20,6 @@ import binaryIndexBy from '../internal/binaryIndexBy';
* _.sortedLastIndex([4, 4, 5, 5], 5);
* // => 4
*/
function sortedLastIndex(array, value, iteratee, thisArg) {
return iteratee == null
? binaryIndex(array, value, true)
: binaryIndexBy(array, value, baseCallback(iteratee, thisArg, 1), true);
}
var sortedLastIndex = createSortedIndex(true);
export default sortedLastIndex;

View File

@@ -1,10 +1,10 @@
import baseCallback from '../internal/baseCallback';
import baseSlice from '../internal/baseSlice';
import baseWhile from '../internal/baseWhile';
/**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is bound to `thisArg`
* and invoked with three arguments; (value, index, array).
* and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -51,13 +51,9 @@ import baseSlice from '../internal/baseSlice';
* // => []
*/
function takeRightWhile(array, predicate, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
predicate = baseCallback(predicate, thisArg, 3);
while (length-- && predicate(array[length], length, array)) {}
return baseSlice(array, length + 1);
return (array && array.length)
? baseWhile(array, baseCallback(predicate, thisArg, 3), false, true)
: [];
}
export default takeRightWhile;

View File

@@ -1,10 +1,10 @@
import baseCallback from '../internal/baseCallback';
import baseSlice from '../internal/baseSlice';
import baseWhile from '../internal/baseWhile';
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is bound to
* `thisArg` and invoked with three arguments; (value, index, array).
* `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -51,14 +51,9 @@ import baseSlice from '../internal/baseSlice';
* // => []
*/
function takeWhile(array, predicate, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
var index = -1;
predicate = baseCallback(predicate, thisArg, 3);
while (++index < length && predicate(array[index], index, array)) {}
return baseSlice(array, 0, index);
return (array && array.length)
? baseWhile(array, baseCallback(predicate, thisArg, 3))
: [];
}
export default takeWhile;

View File

@@ -1,14 +1,11 @@
import baseFlatten from '../internal/baseFlatten';
import baseUniq from '../internal/baseUniq';
import restParam from '../function/restParam';
/**
* Creates an array of unique values, in order, of the provided arrays using
* `SameValueZero` for equality comparisons.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
* Creates an array of unique values, in order, from all of the provided arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
@@ -20,8 +17,8 @@ import baseUniq from '../internal/baseUniq';
* _.union([1, 2], [4, 2], [2, 1]);
* // => [1, 2, 4]
*/
function union() {
return baseUniq(baseFlatten(arguments, false, true));
}
var union = restParam(function(arrays) {
return baseUniq(baseFlatten(arrays, false, true));
});
export default union;

View File

@@ -4,29 +4,26 @@ import isIterateeCall from '../internal/isIterateeCall';
import sortedUniq from '../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`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurence of each element
* is kept. Providing `true` for `isSorted` performs a faster search algorithm
* for sorted arrays. If an iteratee function is provided it's invoked for
* each element in the array to generate the criterion by which uniqueness
* is computed. The `iteratee` is bound to `thisArg` and invoked with three
* arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
*
* @static
* @memberOf _
* @alias unique
@@ -38,8 +35,8 @@ import sortedUniq from '../internal/sortedUniq';
* @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);
@@ -62,7 +59,7 @@ function uniq(array, isSorted, iteratee, thisArg) {
}
if (isSorted != null && typeof isSorted != 'boolean') {
thisArg = iteratee;
iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted;
iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
isSorted = false;
}
iteratee = iteratee == null ? iteratee : baseCallback(iteratee, thisArg, 3);

View File

@@ -1,13 +1,14 @@
import arrayFilter from '../internal/arrayFilter';
import arrayMap from '../internal/arrayMap';
import arrayMax from '../internal/arrayMax';
import baseProperty from '../internal/baseProperty';
import isArrayLike from '../internal/isArrayLike';
/** Used to the length of n-tuples for `_.unzip`. */
var getLength = baseProperty('length');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-`_.zip`
* elements and creates an array regrouping the elements to their pre-zip
* configuration.
*
* @static
@@ -24,10 +25,19 @@ var getLength = baseProperty('length');
* // => [['fred', 'barney'], [30, 40], [true, false]]
*/
function unzip(array) {
if (!(array && array.length)) {
return [];
}
var index = -1,
length = (array && array.length && arrayMax(arrayMap(array, getLength))) >>> 0,
result = Array(length);
length = 0;
array = arrayFilter(array, function(group) {
if (isArrayLike(group)) {
length = nativeMax(group.length, length);
return true;
}
});
var result = Array(length);
while (++index < length) {
result[index] = arrayMap(array, baseProperty(index));
}

41
array/unzipWith.js Normal file
View File

@@ -0,0 +1,41 @@
import arrayMap from '../internal/arrayMap';
import arrayReduce from '../internal/arrayReduce';
import bindCallback from '../internal/bindCallback';
import unzip from './unzip';
/**
* This method is like `_.unzip` except that it accepts an iteratee to specify
* how regrouped values should be combined. The `iteratee` is bound to `thisArg`
* and invoked with four arguments: (accumulator, value, index, group).
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array of grouped elements to process.
* @param {Function} [iteratee] The function to combine regrouped values.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
* // => [[1, 10, 100], [2, 20, 200]]
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
*/
function unzipWith(array, iteratee, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
var result = unzip(array);
if (iteratee == null) {
return result;
}
iteratee = bindCallback(iteratee, thisArg, 4);
return arrayMap(result, function(group) {
return arrayReduce(group, iteratee, undefined, true);
});
}
export default unzipWith;

View File

@@ -1,14 +1,11 @@
import baseDifference from '../internal/baseDifference';
import baseSlice from '../internal/baseSlice';
import isArrayLike from '../internal/isArrayLike';
import restParam from '../function/restParam';
/**
* Creates an array excluding all provided values using `SameValueZero` for
* equality comparisons.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
* Creates an array excluding all provided values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
@@ -21,8 +18,10 @@ import baseSlice from '../internal/baseSlice';
* _.without([1, 2, 1, 3], 1, 2);
* // => [3]
*/
function without(array) {
return baseDifference(array, baseSlice(arguments, 1));
}
var without = restParam(function(array, values) {
return isArrayLike(array)
? baseDifference(array, values)
: [];
});
export default without;

View File

@@ -1,12 +1,11 @@
import arrayPush from '../internal/arrayPush';
import baseDifference from '../internal/baseDifference';
import baseUniq from '../internal/baseUniq';
import isArguments from '../lang/isArguments';
import isArray from '../lang/isArray';
import isArrayLike from '../internal/isArrayLike';
/**
* Creates an array that is the symmetric difference of the provided arrays.
* See [Wikipedia](https://en.wikipedia.org/wiki/Symmetric_difference) for
* more details.
* Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
* of the provided arrays.
*
* @static
* @memberOf _
@@ -24,9 +23,9 @@ function xor() {
while (++index < length) {
var array = arguments[index];
if (isArray(array) || isArguments(array)) {
if (isArrayLike(array)) {
var result = result
? baseDifference(result, array).concat(baseDifference(array, result))
? arrayPush(baseDifference(result, array), baseDifference(array, result))
: array;
}
}

View File

@@ -1,3 +1,4 @@
import restParam from '../function/restParam';
import unzip from './unzip';
/**
@@ -15,14 +16,6 @@ import unzip from './unzip';
* _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*/
function zip() {
var length = arguments.length,
array = Array(length);
while (length--) {
array[length] = arguments[length];
}
return unzip(array);
}
var zip = restParam(unzip);
export default zip;

View File

@@ -1,9 +1,10 @@
import isArray from '../lang/isArray';
/**
* Creates an object composed from arrays of property names and values. Provide
* either a single two dimensional array, e.g. `[[key1, value1], [key2, value2]]`
* or two arrays, one of property names and one of corresponding values.
* The inverse of `_.pairs`; this method returns an object composed from arrays
* of property names and values. Provide either a single two dimensional array,
* e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
* and one of corresponding values.
*
* @static
* @memberOf _
@@ -14,6 +15,9 @@ import isArray from '../lang/isArray';
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject([['fred', 30], ['barney', 40]]);
* // => { 'fred': 30, 'barney': 40 }
*
* _.zipObject(['fred', 'barney'], [30, 40]);
* // => { 'fred': 30, 'barney': 40 }
*/

36
array/zipWith.js Normal file
View File

@@ -0,0 +1,36 @@
import restParam from '../function/restParam';
import unzipWith from './unzipWith';
/**
* This method is like `_.zip` except that it accepts an iteratee to specify
* how grouped values should be combined. The `iteratee` is bound to `thisArg`
* and invoked with four arguments: (accumulator, value, index, group).
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @param {Function} [iteratee] The function to combine grouped values.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zipWith([1, 2], [10, 20], [100, 200], _.add);
* // => [111, 222]
*/
var zipWith = restParam(function(arrays) {
var length = arrays.length,
iteratee = length > 2 ? arrays[length - 2] : undefined,
thisArg = length > 1 ? arrays[length - 1] : undefined;
if (length > 2 && typeof iteratee == 'function') {
length -= 2;
} else {
iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
thisArg = undefined;
}
arrays.length = length;
return unzipWith(arrays, iteratee, thisArg);
});
export default zipWith;

View File

@@ -1,5 +1,6 @@
import chain from './chain/chain';
import commit from './chain/commit';
import concat from './chain/concat';
import lodash from './chain/lodash';
import plant from './chain/plant';
import reverse from './chain/reverse';
@@ -15,6 +16,7 @@ import wrapperChain from './chain/wrapperChain';
export default {
'chain': chain,
'commit': commit,
'concat': concat,
'lodash': lodash,
'plant': plant,
'reverse': reverse,

2
chain/concat.js Normal file
View File

@@ -0,0 +1,2 @@
import wrapperConcat from './wrapperConcat'
export default wrapperConcat;

View File

@@ -14,22 +14,28 @@ var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit chaining.
* Methods that operate on and return arrays, collections, and functions can
* be chained together. Methods that return a boolean or single value will
* automatically end the chain returning the unwrapped value. Explicit chaining
* may be enabled using `_.chain`. The execution of chained methods is lazy,
* that is, execution is deferred until `_#value` is implicitly or explicitly
* called.
* be chained together. Methods that retrieve a single value or may return a
* primitive value will automatically end the chain returning the unwrapped
* value. Explicit chaining may be enabled using `_.chain`. The execution of
* chained methods is lazy, that is, execution is deferred until `_#value`
* is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion. Shortcut
* fusion is an optimization that merges iteratees to avoid creating intermediate
* arrays and reduce the number of iteratee executions.
* fusion is an optimization strategy which merge iteratee calls; this can help
* to avoid the creation of intermediate data structures and greatly reduce the
* number of iteratee executions.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers also have the following `Array` methods:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
* and `unshift`
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
* `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
@@ -40,35 +46,37 @@ var hasOwnProperty = objectProto.hasOwnProperty;
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
* `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
* `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`,
* `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`,
* `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`,
* `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`,
* `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`,
* `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, `merge`,
* `mixin`, `negate`, `noop`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
* `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
* `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
* `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
* `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
* `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
* `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
* `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
* `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
* `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
* `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`,
* `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `splice`, `spread`,
* `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, `throttle`,
* `thru`, `times`, `toArray`, `toPlainObject`, `transform`, `union`, `uniq`,
* `unshift`, `unzip`, `values`, `valuesIn`, `where`, `without`, `wrap`, `xor`,
* `zip`, and `zipObject`
* `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
* `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
* `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
* `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
* `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
* `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`,
* `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`,
* `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `has`,
* `identity`, `includes`, `indexOf`, `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`, `template`, `trim`, `trimLeft`, `trimRight`,
* `trunc`, `unescape`, `uniqueId`, `value`, and `words`
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
* `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
* `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
* `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
* `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
* `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
* `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
* `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
* `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
* `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
* `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
* `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
* `unescape`, `uniqueId`, `value`, and `words`
*
* The wrapper method `sample` will return a wrapped value when `n` is provided,
* otherwise an unwrapped value is returned.
@@ -83,8 +91,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
*

View File

@@ -10,13 +10,14 @@
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _([1, 2, 3])
* .last()
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => [3]
* // => ['abc']
*/
function thru(value, interceptor, thisArg) {
return interceptor.call(thisArg, value);

View File

@@ -10,16 +10,16 @@ import LodashWrapper from '../internal/LodashWrapper';
* @example
*
* var array = [1, 2];
* var wrapper = _(array).push(3);
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapper = wrapper.commit();
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapper.last();
* wrapped.last();
* // => 3
*
* console.log(array);

34
chain/wrapperConcat.js Normal file
View File

@@ -0,0 +1,34 @@
import arrayConcat from '../internal/arrayConcat';
import baseFlatten from '../internal/baseFlatten';
import isArray from '../lang/isArray';
import restParam from '../function/restParam';
import toObject from '../internal/toObject';
/**
* Creates a new array joining a wrapped array with any additional arrays
* and/or values.
*
* @name concat
* @memberOf _
* @category Chain
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var wrapped = _(array).concat(2, [3], [[4]]);
*
* console.log(wrapped.value());
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
*/
var wrapperConcat = restParam(function(values) {
values = baseFlatten(values);
return this.thru(function(array) {
return arrayConcat(isArray(array) ? array : [toObject(array)], values);
});
});
export default wrapperConcat;

View File

@@ -11,17 +11,17 @@ import wrapperClone from '../internal/wrapperClone';
* @example
*
* var array = [1, 2];
* var wrapper = _(array).map(function(value) {
* var wrapped = _(array).map(function(value) {
* return Math.pow(value, 2);
* });
*
* var other = [3, 4];
* var otherWrapper = wrapper.plant(other);
* var otherWrapped = wrapped.plant(other);
*
* otherWrapper.value();
* otherWrapped.value();
* // => [9, 16]
*
* wrapper.value();
* wrapped.value();
* // => [1, 4]
*/
function wrapperPlant(value) {

View File

@@ -24,15 +24,20 @@ import thru from './thru';
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
if (this.__actions__.length) {
value = new LazyWrapper(this);
}
return new LodashWrapper(value.reverse(), this.__chain__);
}
return this.thru(function(value) {
var interceptor = function(value) {
return value.reverse();
});
};
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(interceptor);
}
export default wrapperReverse;

View File

@@ -23,8 +23,8 @@ import indexBy from './collection/indexBy';
import inject from './collection/inject';
import invoke from './collection/invoke';
import map from './collection/map';
import max from './collection/max';
import min from './collection/min';
import max from './math/max';
import min from './math/min';
import partition from './collection/partition';
import pluck from './collection/pluck';
import reduce from './collection/reduce';
@@ -37,6 +37,8 @@ import size from './collection/size';
import some from './collection/some';
import sortBy from './collection/sortBy';
import sortByAll from './collection/sortByAll';
import sortByOrder from './collection/sortByOrder';
import sum from './math/sum';
import where from './collection/where';
export default {
@@ -79,5 +81,7 @@ export default {
'some': some,
'sortBy': sortBy,
'sortByAll': sortByAll,
'sortByOrder': sortByOrder,
'sum': sum,
'where': where
};

View File

@@ -1,7 +1,6 @@
import baseAt from '../internal/baseAt';
import baseFlatten from '../internal/baseFlatten';
import isLength from '../internal/isLength';
import toIterable from '../internal/toIterable';
import restParam from '../function/restParam';
/**
* Creates an array of elements corresponding to the given keys, or indexes,
@@ -20,15 +19,11 @@ import toIterable from '../internal/toIterable';
* _.at(['a', 'b', 'c'], [0, 2]);
* // => ['a', 'c']
*
* _.at(['fred', 'barney', 'pebbles'], 0, 2);
* // => ['fred', 'pebbles']
* _.at(['barney', 'fred', 'pebbles'], 0, 2);
* // => ['barney', 'pebbles']
*/
function at(collection) {
var length = collection ? collection.length : 0;
if (isLength(length)) {
collection = toIterable(collection);
}
return baseAt(collection, baseFlatten(arguments, false, false, 1));
}
var at = restParam(function(collection, props) {
return baseAt(collection, baseFlatten(props));
});
export default at;

View File

@@ -10,17 +10,17 @@ var hasOwnProperty = objectProto.hasOwnProperty;
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is the number of times the key was returned by `iteratee`.
* The `iteratee` is bound to `thisArg` and invoked with three arguments;
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*

View File

@@ -2,10 +2,11 @@ import arrayEvery from '../internal/arrayEvery';
import baseCallback from '../internal/baseCallback';
import baseEvery from '../internal/baseEvery';
import isArray from '../lang/isArray';
import isIterateeCall from '../internal/isIterateeCall';
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* The predicate is bound to `thisArg` and invoked with three arguments;
* The predicate is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
@@ -53,7 +54,10 @@ import isArray from '../lang/isArray';
*/
function every(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (typeof predicate != 'function' || typeof thisArg != 'undefined') {
if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
predicate = undefined;
}
if (typeof predicate != 'function' || thisArg !== undefined) {
predicate = baseCallback(predicate, thisArg, 3);
}
return func(collection, predicate);

View File

@@ -6,7 +6,7 @@ import isArray from '../lang/isArray';
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
* invoked with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.

View File

@@ -1,13 +1,10 @@
import baseCallback from '../internal/baseCallback';
import baseEach from '../internal/baseEach';
import baseFind from '../internal/baseFind';
import findIndex from '../array/findIndex';
import isArray from '../lang/isArray';
import createFind from '../internal/createFind';
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
* invoked with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -54,13 +51,6 @@ import isArray from '../lang/isArray';
* _.result(_.find(users, 'active'), 'user');
* // => 'barney'
*/
function find(collection, predicate, thisArg) {
if (isArray(collection)) {
var index = findIndex(collection, predicate, thisArg);
return index > -1 ? collection[index] : undefined;
}
predicate = baseCallback(predicate, thisArg, 3);
return baseFind(collection, predicate, baseEach);
}
var find = createFind(baseEach);
export default find;

View File

@@ -1,6 +1,5 @@
import baseCallback from '../internal/baseCallback';
import baseEachRight from '../internal/baseEachRight';
import baseFind from '../internal/baseFind';
import createFind from '../internal/createFind';
/**
* This method is like `_.find` except that it iterates over elements of
@@ -21,9 +20,6 @@ import baseFind from '../internal/baseFind';
* });
* // => 3
*/
function findLast(collection, predicate, thisArg) {
predicate = baseCallback(predicate, thisArg, 3);
return baseFind(collection, predicate, baseEachRight);
}
var findLast = createFind(baseEachRight, true);
export default findLast;

View File

@@ -1,15 +1,14 @@
import arrayEach from '../internal/arrayEach';
import baseEach from '../internal/baseEach';
import bindCallback from '../internal/bindCallback';
import isArray from '../lang/isArray';
import createForEach from '../internal/createForEach';
/**
* 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
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection). Iteratee functions may exit iteration early
* by explicitly returning `false`.
*
* **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.
*
@@ -33,10 +32,6 @@ import isArray from '../lang/isArray';
* });
* // => logs each value-key pair and returns the object (iteration order is not guaranteed)
*/
function forEach(collection, iteratee, thisArg) {
return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection))
? arrayEach(collection, iteratee)
: baseEach(collection, bindCallback(iteratee, thisArg, 3));
}
var forEach = createForEach(arrayEach, baseEach);
export default forEach;

View File

@@ -1,7 +1,6 @@
import arrayEachRight from '../internal/arrayEachRight';
import baseEachRight from '../internal/baseEachRight';
import bindCallback from '../internal/bindCallback';
import isArray from '../lang/isArray';
import createForEach from '../internal/createForEach';
/**
* This method is like `_.forEach` except that it iterates over elements of
@@ -19,13 +18,9 @@ import isArray from '../lang/isArray';
*
* _([1, 2]).forEachRight(function(n) {
* console.log(n);
* }).join(',');
* }).value();
* // => logs each value from right to left and returns the array
*/
function forEachRight(collection, iteratee, thisArg) {
return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection))
? arrayEachRight(collection, iteratee)
: baseEachRight(collection, bindCallback(iteratee, thisArg, 3));
}
var forEachRight = createForEach(arrayEachRight, baseEachRight);
export default forEachRight;

View File

@@ -10,17 +10,17 @@ var hasOwnProperty = objectProto.hasOwnProperty;
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is an array of the elements responsible for generating the key.
* The `iteratee` is bound to `thisArg` and invoked with three arguments;
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*

View File

@@ -1,5 +1,7 @@
import baseIndexOf from '../internal/baseIndexOf';
import getLength from '../internal/getLength';
import isArray from '../lang/isArray';
import isIterateeCall from '../internal/isIterateeCall';
import isLength from '../internal/isLength';
import isString from '../lang/isString';
import values from '../object/values';
@@ -8,14 +10,10 @@ import values from '../object/values';
var nativeMax = Math.max;
/**
* Checks if `value` is in `collection` using `SameValueZero` for equality
* comparisons. If `fromIndex` is negative, it is used as the offset from
* the end of `collection`.
*
* **Note:** `SameValueZero` comparisons are like strict equality comparisons,
* e.g. `===`, except that `NaN` matches `NaN`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* for more details.
* Checks if `target` is in `collection` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the offset
* from the end of `collection`.
*
* @static
* @memberOf _
@@ -24,6 +22,7 @@ var nativeMax = Math.max;
* @param {Array|Object|string} collection The collection to search.
* @param {*} target The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
* @returns {boolean} Returns `true` if a matching element is found, else `false`.
* @example
*
@@ -39,23 +38,20 @@ var nativeMax = Math.max;
* _.includes('pebbles', 'eb');
* // => true
*/
function includes(collection, target, fromIndex) {
var length = collection ? collection.length : 0;
function includes(collection, target, fromIndex, guard) {
var length = collection ? getLength(collection) : 0;
if (!isLength(length)) {
collection = values(collection);
length = collection.length;
}
if (!length) {
return false;
}
if (typeof fromIndex == 'number') {
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
} else {
if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
fromIndex = 0;
} else {
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
}
return (typeof collection == 'string' || !isArray(collection) && isString(collection))
? (fromIndex < length && collection.indexOf(target, fromIndex) > -1)
: (baseIndexOf(collection, target, fromIndex) > -1);
? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
: (!!length && baseIndexOf(collection, target, fromIndex) > -1);
}
export default includes;

View File

@@ -4,17 +4,17 @@ import createAggregator from '../internal/createAggregator';
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is the last element responsible for generating the key. The
* iteratee function is bound to `thisArg` and invoked with three arguments;
* iteratee function is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*

View File

@@ -1,17 +1,20 @@
import baseInvoke from '../internal/baseInvoke';
import baseSlice from '../internal/baseSlice';
import baseEach from '../internal/baseEach';
import invokePath from '../internal/invokePath';
import isArrayLike from '../internal/isArrayLike';
import isKey from '../internal/isKey';
import restParam from '../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` of each element in `collection`, returning
* an array of the results of each invoked method. Any additional arguments
* are provided to each invoked method. If `methodName` is a function it's
* 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.
@@ -23,8 +26,17 @@ import baseSlice from '../internal/baseSlice';
* _.invoke([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
function invoke(collection, methodName) {
return baseInvoke(collection, methodName, baseSlice(arguments, 2));
}
var invoke = restParam(function(collection, path, args) {
var index = -1,
isFunc = typeof path == 'function',
isProp = isKey(path),
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value) {
var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
});
return result;
});
export default invoke;

View File

@@ -6,27 +6,28 @@ import isArray from '../lang/isArray';
/**
* Creates an array of values by running each element in `collection` through
* `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection).
* arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* Many lodash methods are guarded to work as interatees for methods like
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, `drop`,
* `dropRight`, `fill`, `flatten`, `invert`, `max`, `min`, `parseInt`, `slice`,
* `sortBy`, `take`, `takeRight`, `template`, `trim`, `trimLeft`, `trimRight`,
* `trunc`, `random`, `range`, `sample`, `uniq`, and `words`
* `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
* `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
* `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
* `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
* `sum`, `uniq`, and `words`
*
* @static
* @memberOf _
@@ -35,7 +36,6 @@ import isArray from '../lang/isArray';
* @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

View File

@@ -1,53 +1,2 @@
import arrayMax from '../internal/arrayMax';
import createExtremum from '../internal/createExtremum';
/**
* Gets the maximum value of `collection`. If `collection` is empty or falsey
* `-Infinity` is returned. If an iteratee function is provided it is invoked
* for each value in `collection` to generate the criterion by which the value
* is ranked. The `iteratee` is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => -Infinity
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* _.max(users, function(chr) {
* return chr.age;
* });
* // => { 'user': 'fred', 'age': 40 };
*
* // using the `_.property` callback shorthand
* _.max(users, 'age');
* // => { 'user': 'fred', 'age': 40 };
*/
var max = createExtremum(arrayMax);
import max from '../math/max'
export default max;

View File

@@ -1,53 +1,2 @@
import arrayMin from '../internal/arrayMin';
import createExtremum from '../internal/createExtremum';
/**
* Gets the minimum value of `collection`. If `collection` is empty or falsey
* `Infinity` is returned. If an iteratee function is provided it is invoked
* for each value in `collection` to generate the criterion by which the value
* is ranked. The `iteratee` is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => Infinity
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* _.min(users, function(chr) {
* return chr.age;
* });
* // => { 'user': 'barney', 'age': 36 };
*
* // using the `_.property` callback shorthand
* _.min(users, 'age');
* // => { 'user': 'barney', 'age': 36 };
*/
var min = createExtremum(arrayMin, true);
import min from '../math/min'
export default min;

View File

@@ -4,7 +4,7 @@ import createAggregator from '../internal/createAggregator';
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, while the second of which
* contains elements `predicate` returns falsey for. The predicate is bound
* to `thisArg` and invoked with three arguments; (value, index|key, collection).
* to `thisArg` and invoked with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -35,7 +35,7 @@ import createAggregator from '../internal/createAggregator';
* _.partition([1.2, 2.3, 3.4], function(n) {
* return this.floor(n) % 2;
* }, Math);
* // => [[1, 3], [2]]
* // => [[1.2, 3.4], [2.3]]
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },

View File

@@ -1,14 +1,14 @@
import baseProperty from '../internal/baseProperty';
import map from './map';
import property from '../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 @@ import map from './map';
* _.pluck(userIndex, 'age');
* // => [36, 40] (iteration order is not guaranteed)
*/
function pluck(collection, key) {
return map(collection, baseProperty(key));
function pluck(collection, path) {
return map(collection, property(path));
}
export default pluck;

View File

@@ -1,22 +1,21 @@
import arrayReduce from '../internal/arrayReduce';
import baseCallback from '../internal/baseCallback';
import baseEach from '../internal/baseEach';
import baseReduce from '../internal/baseReduce';
import isArray from '../lang/isArray';
import createReduce from '../internal/createReduce';
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` through `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not provided the first element of `collection` is used as the initial
* value. The `iteratee` is bound to `thisArg`and invoked with four arguments;
* value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as interatees for methods like
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `merge`, and `sortAllBy`
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
* and `sortByOrder`
*
* @static
* @memberOf _
@@ -29,8 +28,8 @@ import isArray from '../lang/isArray';
* @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
*
@@ -40,9 +39,6 @@ import isArray from '../lang/isArray';
* }, {});
* // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator, thisArg) {
var func = isArray(collection) ? arrayReduce : baseReduce;
return func(collection, baseCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEach);
}
var reduce = createReduce(arrayReduce, baseEach);
export default reduce;

View File

@@ -1,8 +1,6 @@
import arrayReduceRight from '../internal/arrayReduceRight';
import baseCallback from '../internal/baseCallback';
import baseEachRight from '../internal/baseEachRight';
import baseReduce from '../internal/baseReduce';
import isArray from '../lang/isArray';
import createReduce from '../internal/createReduce';
/**
* This method is like `_.reduce` except that it iterates over elements of
@@ -26,9 +24,6 @@ import isArray from '../lang/isArray';
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, iteratee, accumulator, thisArg) {
var func = isArray(collection) ? arrayReduceRight : baseReduce;
return func(collection, baseCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEachRight);
}
var reduceRight = createReduce(arrayReduceRight, baseEachRight);
export default reduceRight;

View File

@@ -7,17 +7,6 @@ import isArray from '../lang/isArray';
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection

View File

@@ -1,6 +1,6 @@
import baseRandom from '../internal/baseRandom';
import isIterateeCall from '../internal/isIterateeCall';
import shuffle from './shuffle';
import toArray from '../lang/toArray';
import toIterable from '../internal/toIterable';
/* Native method references for those with the same name as other `lodash` methods. */
@@ -30,8 +30,20 @@ function sample(collection, n, guard) {
var length = collection.length;
return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
}
var result = shuffle(collection);
result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length);
var index = -1,
result = toArray(collection),
length = result.length,
lastIndex = length - 1;
n = nativeMin(n < 0 ? 0 : (+n || 0), length);
while (++index < n) {
var rand = baseRandom(index, lastIndex),
value = result[rand];
result[rand] = result[index];
result[index] = value;
}
result.length = n;
return result;
}

View File

@@ -1,10 +1,11 @@
import baseRandom from '../internal/baseRandom';
import toIterable from '../internal/toIterable';
import sample from './sample';
/** Used as references for `-Infinity` and `Infinity`. */
var POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
/**
* Creates an array of shuffled values, using a version of the Fisher-Yates
* shuffle. See [Wikipedia](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle)
* for more details.
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
@@ -17,20 +18,7 @@ import toIterable from '../internal/toIterable';
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
collection = toIterable(collection);
var index = -1,
length = collection.length,
result = Array(length);
while (++index < length) {
var rand = baseRandom(0, index);
if (index != rand) {
result[index] = result[rand];
}
result[rand] = collection[index];
}
return result;
return sample(collection, POSITIVE_INFINITY);
}
export default shuffle;

View File

@@ -1,9 +1,10 @@
import getLength from '../internal/getLength';
import isLength from '../internal/isLength';
import keys from '../object/keys';
/**
* Gets the size of `collection` by returning `collection.length` for
* array-like values or the number of own enumerable properties for objects.
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable properties for objects.
*
* @static
* @memberOf _
@@ -22,7 +23,7 @@ import keys from '../object/keys';
* // => 7
*/
function size(collection) {
var length = collection ? collection.length : 0;
var length = collection ? getLength(collection) : 0;
return isLength(length) ? length : keys(collection).length;
}

View File

@@ -2,12 +2,13 @@ import arraySome from '../internal/arraySome';
import baseCallback from '../internal/baseCallback';
import baseSome from '../internal/baseSome';
import isArray from '../lang/isArray';
import isIterateeCall from '../internal/isIterateeCall';
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* The function returns as soon as it finds a passing value and does not iterate
* over the entire collection. The predicate is bound to `thisArg` and invoked
* with three arguments; (value, index|key, collection).
* with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
@@ -54,7 +55,10 @@ import isArray from '../lang/isArray';
*/
function some(collection, predicate, thisArg) {
var func = isArray(collection) ? arraySome : baseSome;
if (typeof predicate != 'function' || typeof thisArg != 'undefined') {
if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
predicate = undefined;
}
if (typeof predicate != 'function' || thisArg !== undefined) {
predicate = baseCallback(predicate, thisArg, 3);
}
return func(collection, predicate);

View File

@@ -1,25 +1,24 @@
import baseCallback from '../internal/baseCallback';
import baseEach from '../internal/baseEach';
import baseMap from '../internal/baseMap';
import baseSortBy from '../internal/baseSortBy';
import compareAscending from '../internal/compareAscending';
import isIterateeCall from '../internal/isIterateeCall';
import isLength from '../internal/isLength';
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection through `iteratee`. This method performs
* a stable sort, that is, it preserves the original sort order of equal elements.
* The `iteratee` is bound to `thisArg` and invoked with three arguments;
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
@@ -27,9 +26,8 @@ import isLength from '../internal/isLength';
* @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
@@ -55,16 +53,17 @@ import isLength from '../internal/isLength';
* // => ['barney', 'fred', 'pebbles']
*/
function sortBy(collection, iteratee, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = isLength(length) ? Array(length) : [];
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = null;
if (collection == null) {
return [];
}
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = undefined;
}
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);
}

View File

@@ -1,53 +1,52 @@
import baseEach from '../internal/baseEach';
import baseFlatten from '../internal/baseFlatten';
import baseSortBy from '../internal/baseSortBy';
import compareMultipleAscending from '../internal/compareMultipleAscending';
import baseSortByOrder from '../internal/baseSortByOrder';
import isIterateeCall from '../internal/isIterateeCall';
import isLength from '../internal/isLength';
import restParam from '../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(collection) {
var args = arguments;
if (args.length > 3 && isIterateeCall(args[1], args[2], args[3])) {
args = [collection, args[1]];
var sortByAll = restParam(function(collection, iteratees) {
if (collection == null) {
return [];
}
var index = -1,
length = collection ? collection.length : 0,
props = baseFlatten(args, false, false, 1),
result = isLength(length) ? Array(length) : [];
baseEach(collection, function(value) {
var length = props.length,
criteria = Array(length);
while (length--) {
criteria[length] = value == null ? undefined : value[props[length]];
}
result[++index] = { 'criteria': criteria, 'index': index, 'value': value };
});
return baseSortBy(result, compareMultipleAscending);
}
var guard = iteratees[2];
if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
iteratees.length = 1;
}
return baseSortByOrder(collection, baseFlatten(iteratees), []);
});
export default sortByAll;

55
collection/sortByOrder.js Normal file
View File

@@ -0,0 +1,55 @@
import baseSortByOrder from '../internal/baseSortByOrder';
import isArray from '../lang/isArray';
import isIterateeCall from '../internal/isIterateeCall';
/**
* This method is like `_.sortByAll` except that it allows specifying the
* sort orders of the iteratees to sort by. If `orders` is unspecified, all
* values are sorted in ascending order. Otherwise, a value is sorted in
* ascending order if its corresponding order is "asc", and descending if "desc".
*
* If a property name is provided for an iteratee the created `_.property`
* style callback returns the property value of the given element.
*
* If an object is provided for an iteratee the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {boolean[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 42 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // sort by `user` in ascending order and by `age` in descending order
* _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
* // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
*/
function sortByOrder(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (guard && isIterateeCall(iteratees, orders, guard)) {
orders = undefined;
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseSortByOrder(collection, iteratees, orders);
}
export default sortByOrder;

2
collection/sum.js Normal file
View File

@@ -0,0 +1,2 @@
import sum from '../math/sum'
export default sum;

View File

@@ -1,7 +1,7 @@
import isNative from '../lang/isNative';
import getNative from '../internal/getNative';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeNow = isNative(nativeNow = Date.now) && nativeNow;
var nativeNow = getNative(Date, 'now');
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch

View File

@@ -14,11 +14,13 @@ import delay from './function/delay';
import flow from './function/flow';
import flowRight from './function/flowRight';
import memoize from './function/memoize';
import modArgs from './function/modArgs';
import negate from './function/negate';
import once from './function/once';
import partial from './function/partial';
import partialRight from './function/partialRight';
import rearg from './function/rearg';
import restParam from './function/restParam';
import spread from './function/spread';
import throttle from './function/throttle';
import wrap from './function/wrap';
@@ -40,11 +42,13 @@ export default {
'flow': flow,
'flowRight': flowRight,
'memoize': memoize,
'modArgs': modArgs,
'negate': negate,
'once': once,
'partial': partial,
'partialRight': partialRight,
'rearg': rearg,
'restParam': restParam,
'spread': spread,
'throttle': throttle,
'wrap': wrap

View File

@@ -8,7 +8,7 @@ var nativeIsFinite = root.isFinite;
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it is called `n` or more times.
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _

View File

@@ -2,7 +2,7 @@ import createWrapper from '../internal/createWrapper';
import isIterateeCall from '../internal/isIterateeCall';
/** Used to compose bitmasks for wrapper metadata. */
var ARY_FLAG = 256;
var ARY_FLAG = 128;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
@@ -25,10 +25,10 @@ var nativeMax = Math.max;
*/
function ary(func, n, guard) {
if (guard && isIterateeCall(func, n, guard)) {
n = null;
n = undefined;
}
n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
return createWrapper(func, ARY_FLAG, null, null, null, null, n);
return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
}
export default ary;

View File

@@ -3,7 +3,7 @@ var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it is called less than `n` times. Subsequent
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
@@ -31,8 +31,9 @@ function before(n, func) {
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
} else {
func = null;
}
if (n <= 1) {
func = undefined;
}
return result;
};

View File

@@ -1,6 +1,6 @@
import baseSlice from '../internal/baseSlice';
import createWrapper from '../internal/createWrapper';
import replaceHolders from '../internal/replaceHolders';
import restParam from './restParam';
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
@@ -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
@@ -22,7 +22,7 @@ var BIND_FLAG = 1,
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [args] The arguments to be partially applied.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
@@ -41,16 +41,14 @@ var BIND_FLAG = 1,
* bound('hi');
* // => 'hi fred!'
*/
function bind(func, thisArg) {
var bind = restParam(function(func, thisArg, partials) {
var bitmask = BIND_FLAG;
if (arguments.length > 2) {
var partials = baseSlice(arguments, 2),
holders = replaceHolders(partials, bind.placeholder);
if (partials.length) {
var holders = replaceHolders(partials, bind.placeholder);
bitmask |= PARTIAL_FLAG;
}
return createWrapper(func, bitmask, thisArg, partials, holders);
}
});
// Assign default placeholders.
bind.placeholder = {};

View File

@@ -1,6 +1,10 @@
import baseBindAll from '../internal/baseBindAll';
import baseFlatten from '../internal/baseFlatten';
import createWrapper from '../internal/createWrapper';
import functions from '../object/functions';
import restParam from './restParam';
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1;
/**
* Binds methods of an object to the object itself, overwriting the existing
@@ -8,7 +12,7 @@ import functions from '../object/functions';
* 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 _
@@ -30,12 +34,17 @@ import functions from '../object/functions';
* jQuery('#docs').on('click', view.onClick);
* // => logs 'clicked docs' when the element is clicked
*/
function bindAll(object) {
return baseBindAll(object,
arguments.length > 1
? baseFlatten(arguments, false, false, 1)
: functions(object)
);
}
var bindAll = restParam(function(object, methodNames) {
methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
var index = -1,
length = methodNames.length;
while (++index < length) {
var key = methodNames[index];
object[key] = createWrapper(object[key], BIND_FLAG, object);
}
return object;
});
export default bindAll;

View File

@@ -1,6 +1,6 @@
import baseSlice from '../internal/baseSlice';
import createWrapper from '../internal/createWrapper';
import replaceHolders from '../internal/replaceHolders';
import restParam from './restParam';
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
@@ -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
@@ -24,7 +24,7 @@ var BIND_FLAG = 1,
* @category Function
* @param {Object} object The object the method belongs to.
* @param {string} key The key of the method.
* @param {...*} [args] The arguments to be partially applied.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
@@ -51,16 +51,14 @@ var BIND_FLAG = 1,
* bound('hi');
* // => 'hiya fred!'
*/
function bindKey(object, key) {
var bindKey = restParam(function(object, key, partials) {
var bitmask = BIND_FLAG | BIND_KEY_FLAG;
if (arguments.length > 2) {
var partials = baseSlice(arguments, 2),
holders = replaceHolders(partials, bindKey.placeholder);
if (partials.length) {
var holders = replaceHolders(partials, bindKey.placeholder);
bitmask |= PARTIAL_FLAG;
}
return createWrapper(key, bitmask, object, partials, holders);
}
});
// Assign default placeholders.
bindKey.placeholder = {};

View File

@@ -1,5 +1,4 @@
import createWrapper from '../internal/createWrapper';
import isIterateeCall from '../internal/isIterateeCall';
import createCurry from '../internal/createCurry';
/** Used to compose bitmasks for wrapper metadata. */
var CURRY_FLAG = 8;
@@ -14,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 _
@@ -44,14 +43,7 @@ var CURRY_FLAG = 8;
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
if (guard && isIterateeCall(func, arity, guard)) {
arity = null;
}
var result = createWrapper(func, CURRY_FLAG, null, null, null, null, null, arity);
result.placeholder = curry.placeholder;
return result;
}
var curry = createCurry(CURRY_FLAG);
// Assign default placeholders.
curry.placeholder = {};

View File

@@ -1,5 +1,4 @@
import createWrapper from '../internal/createWrapper';
import isIterateeCall from '../internal/isIterateeCall';
import createCurry from '../internal/createCurry';
/** Used to compose bitmasks for wrapper metadata. */
var CURRY_RIGHT_FLAG = 16;
@@ -11,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 _
@@ -41,14 +40,7 @@ var CURRY_RIGHT_FLAG = 16;
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
function curryRight(func, arity, guard) {
if (guard && isIterateeCall(func, arity, guard)) {
arity = null;
}
var result = createWrapper(func, CURRY_RIGHT_FLAG, null, null, null, null, null, arity);
result.placeholder = curryRight.placeholder;
return result;
}
var curryRight = createCurry(CURRY_RIGHT_FLAG);
// Assign default placeholders.
curryRight.placeholder = {};

View File

@@ -8,12 +8,13 @@ var FUNC_ERROR_TEXT = 'Expected a function';
var nativeMax = Math.max;
/**
* Creates a function that delays invoking `func` until after `wait` milliseconds
* have elapsed since the last time it was invoked. The created function comes
* with a `cancel` method to cancel delayed invocations. Provide an options
* object to indicate that `func` should be invoked on the leading and/or
* trailing edge of the `wait` timeout. Subsequent calls to the debounced
* function return the result of the last `func` invocation.
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the debounced function return the result of the last
* `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
@@ -31,7 +32,7 @@ var nativeMax = Math.max;
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it is invoked.
* delayed before it's invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
@@ -89,9 +90,9 @@ function debounce(func, wait, options) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = options.leading;
leading = !!options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? options.trailing : trailing;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function cancel() {
@@ -101,41 +102,35 @@ function debounce(func, wait, options) {
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
lastCalled = 0;
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function complete(isCalled, id) {
if (id) {
clearTimeout(id);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
}
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
var isCalled = trailingCall;
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
complete(trailingCall, maxTimeoutId);
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
if (timeoutId) {
clearTimeout(timeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (trailing || (maxWait !== wait)) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
complete(trailing, timeoutId);
}
function debounced() {
@@ -175,7 +170,7 @@ function debounce(func, wait, options) {
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = null;
args = thisArg = undefined;
}
return result;
}

View File

@@ -1,8 +1,9 @@
import baseDelay from '../internal/baseDelay';
import restParam from './restParam';
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it is invoked.
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
@@ -17,8 +18,8 @@ import baseDelay from '../internal/baseDelay';
* }, 'deferred');
* // logs 'deferred' after one or more milliseconds
*/
function defer(func) {
return baseDelay(func, 1, arguments, 1);
}
var defer = restParam(function(func, args) {
return baseDelay(func, 1, args);
});
export default defer;

View File

@@ -1,8 +1,9 @@
import baseDelay from '../internal/baseDelay';
import restParam from './restParam';
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it is invoked.
* provided to `func` when it's invoked.
*
* @static
* @memberOf _
@@ -18,8 +19,8 @@ import baseDelay from '../internal/baseDelay';
* }, 1000, 'later');
* // => logs 'later' after one second
*/
function delay(func, wait) {
return baseDelay(func, wait, arguments, 2);
}
var delay = restParam(function(func, wait, args) {
return baseDelay(func, wait, args);
});
export default delay;

View File

@@ -1,8 +1,4 @@
import arrayEvery from '../internal/arrayEvery';
import baseIsFunction from '../internal/baseIsFunction';
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
import createFlow from '../internal/createFlow';
/**
* Creates a function that returns the result of invoking the provided
@@ -16,37 +12,14 @@ var FUNC_ERROR_TEXT = 'Expected a function';
* @returns {Function} Returns the new function.
* @example
*
* function add(x, y) {
* return x + y;
* }
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow(add, square);
* var addSquare = _.flow(_.add, square);
* addSquare(1, 2);
* // => 9
*/
function flow() {
var funcs = arguments,
length = funcs.length;
if (!length) {
return function() { return arguments[0]; };
}
if (!arrayEvery(funcs, baseIsFunction)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var index = 0,
result = funcs[index].apply(this, arguments);
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
}
var flow = createFlow();
export default flow;

View File

@@ -1,8 +1,4 @@
import arrayEvery from '../internal/arrayEvery';
import baseIsFunction from '../internal/baseIsFunction';
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
import createFlow from '../internal/createFlow';
/**
* This method is like `_.flow` except that it creates a function that
@@ -16,37 +12,14 @@ var FUNC_ERROR_TEXT = 'Expected a function';
* @returns {Function} Returns the new function.
* @example
*
* function add(x, y) {
* return x + y;
* }
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight(square, add);
* var addSquare = _.flowRight(square, _.add);
* addSquare(1, 2);
* // => 9
*/
function flowRight() {
var funcs = arguments,
fromIndex = funcs.length - 1;
if (fromIndex < 0) {
return function() { return arguments[0]; };
}
if (!arrayEvery(funcs, baseIsFunction)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var index = fromIndex,
result = funcs[index].apply(this, arguments);
while (index--) {
result = funcs[index].call(this, result);
}
return result;
};
}
var flowRight = createFlow(true);
export default flowRight;

View File

@@ -13,10 +13,8 @@ var FUNC_ERROR_TEXT = 'Expected a function';
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the ES `Map` method interface
* of `get`, `has`, and `set`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object)
* for more details.
* constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
* method interface of `get`, `has`, and `set`.
*
* @static
* @memberOf _
@@ -61,14 +59,15 @@ function memoize(func, resolver) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : arguments[0];
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, arguments);
cache.set(key, result);
var result = func.apply(this, args);
memoized.cache = cache.set(key, result);
return result;
};
memoized.cache = new memoize.Cache;

58
function/modArgs.js Normal file
View File

@@ -0,0 +1,58 @@
import arrayEvery from '../internal/arrayEvery';
import baseFlatten from '../internal/baseFlatten';
import baseIsFunction from '../internal/baseIsFunction';
import restParam from './restParam';
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Creates a function that runs each argument through a corresponding
* transform function.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to wrap.
* @param {...(Function|Function[])} [transforms] The functions to transform
* arguments, specified as individual functions or arrays of functions.
* @returns {Function} Returns the new function.
* @example
*
* function doubled(n) {
* return n * 2;
* }
*
* function square(n) {
* return n * n;
* }
*
* var modded = _.modArgs(function(x, y) {
* return [x, y];
* }, square, doubled);
*
* modded(1, 2);
* // => [1, 4]
*
* modded(5, 10);
* // => [25, 20]
*/
var modArgs = restParam(function(func, transforms) {
transforms = baseFlatten(transforms);
if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = transforms.length;
return restParam(function(args) {
var index = nativeMin(args.length, length);
while (index--) {
args[index] = transforms[index](args[index]);
}
return func.apply(this, args);
});
});
export default modArgs;

View File

@@ -3,7 +3,7 @@ import before from './before';
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first call. The `func` is invoked
* with the `this` binding of the created function.
* with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
@@ -18,7 +18,7 @@ import before from './before';
* // `initialize` invokes `createApplication` once
*/
function once(func) {
return before(func, 2);
return before(2, func);
}
export default once;

View File

@@ -1,6 +1,4 @@
import baseSlice from '../internal/baseSlice';
import createWrapper from '../internal/createWrapper';
import replaceHolders from '../internal/replaceHolders';
import createPartial from '../internal/createPartial';
/** Used to compose bitmasks for wrapper metadata. */
var PARTIAL_FLAG = 32;
@@ -13,14 +11,14 @@ 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
* @memberOf _
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [args] The arguments to be partially applied.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
@@ -37,12 +35,7 @@ var PARTIAL_FLAG = 32;
* greetFred('hi');
* // => 'hi fred'
*/
function partial(func) {
var partials = baseSlice(arguments, 1),
holders = replaceHolders(partials, partial.placeholder);
return createWrapper(func, PARTIAL_FLAG, null, partials, holders);
}
var partial = createPartial(PARTIAL_FLAG);
// Assign default placeholders.
partial.placeholder = {};

View File

@@ -1,6 +1,4 @@
import baseSlice from '../internal/baseSlice';
import createWrapper from '../internal/createWrapper';
import replaceHolders from '../internal/replaceHolders';
import createPartial from '../internal/createPartial';
/** Used to compose bitmasks for wrapper metadata. */
var PARTIAL_RIGHT_FLAG = 64;
@@ -12,14 +10,14 @@ 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
* @memberOf _
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [args] The arguments to be partially applied.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
@@ -36,12 +34,7 @@ var PARTIAL_RIGHT_FLAG = 64;
* sayHelloTo('fred');
* // => 'hello fred'
*/
function partialRight(func) {
var partials = baseSlice(arguments, 1),
holders = replaceHolders(partials, partialRight.placeholder);
return createWrapper(func, PARTIAL_RIGHT_FLAG, null, partials, holders);
}
var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
// Assign default placeholders.
partialRight.placeholder = {};

View File

@@ -1,8 +1,9 @@
import baseFlatten from '../internal/baseFlatten';
import createWrapper from '../internal/createWrapper';
import restParam from './restParam';
/** Used to compose bitmasks for wrapper metadata. */
var REARG_FLAG = 128;
var REARG_FLAG = 256;
/**
* Creates a function that invokes `func` with arguments arranged according
@@ -32,9 +33,8 @@ var REARG_FLAG = 128;
* }, [1, 2, 3]);
* // => [3, 6, 9]
*/
function rearg(func) {
var indexes = baseFlatten(arguments, false, false, 1);
return createWrapper(func, REARG_FLAG, null, null, null, indexes);
}
var rearg = restParam(function(func, indexes) {
return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
});
export default rearg;

58
function/restParam.js Normal file
View File

@@ -0,0 +1,58 @@
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
export default restParam;

View File

@@ -2,23 +2,24 @@
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and the array of arguments provided to the created
* function much like [Function#apply](http://es5.github.io/#x15.3.4.3).
* Creates a function that invokes `func` with the `this` binding of the created
* function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
*
* **Note:** This method is based on the [spread operator](https://developer.mozilla.org/Web/JavaScript/Reference/Operators/Spread_operator).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to spread arguments over.
* @returns {*} Returns the new function.
* @returns {Function} Returns the new function.
* @example
*
* var spread = _.spread(function(who, what) {
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* spread(['Fred', 'hello']);
* // => 'Fred says hello'
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* // with a Promise
* var numbers = Promise.all([

View File

@@ -4,20 +4,13 @@ import isObject from '../lang/isObject';
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as an internal `_.debounce` options object by `_.throttle`. */
var debounceOptions = {
'leading': false,
'maxWait': 0,
'trailing': false
};
/**
* Creates a function that only invokes `func` at most once per every `wait`
* milliseconds. The created function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the throttled function return the result of the last
* `func` call.
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed invocations. Provide an options object to indicate
* that `func` should be invoked on the leading and/or trailing edge of the
* `wait` timeout. Subsequent calls to the throttled function return the
* result of the last `func` call.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the throttled function is
@@ -63,10 +56,7 @@ function throttle(func, wait, options) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
debounceOptions.leading = leading;
debounceOptions.maxWait = +wait;
debounceOptions.trailing = trailing;
return debounce(func, wait, debounceOptions);
return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
}
export default throttle;

View File

@@ -27,7 +27,7 @@ var PARTIAL_FLAG = 32;
*/
function wrap(value, wrapper) {
wrapper = wrapper == null ? identity : wrapper;
return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []);
return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
}
export default wrap;

View File

@@ -12,13 +12,12 @@ var POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = null;
this.__actions__ = [];
this.__dir__ = 1;
this.__dropCount__ = 0;
this.__filtered__ = false;
this.__iteratees__ = null;
this.__iteratees__ = [];
this.__takeCount__ = POSITIVE_INFINITY;
this.__views__ = null;
this.__views__ = [];
}
LazyWrapper.prototype = baseCreate(baseLodash.prototype);

View File

@@ -1,12 +1,12 @@
import cachePush from './cachePush';
import isNative from '../lang/isNative';
import getNative from './getNative';
import root from './root';
/** Native method references. */
var Set = isNative(Set = root.Set) && Set;
var Set = getNative(root, 'Set');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate;
var nativeCreate = getNative(Object, 'create');
/**
*

25
internal/arrayConcat.js Normal file
View File

@@ -0,0 +1,25 @@
/**
* Creates a new array joining `array` with `other`.
*
* @private
* @param {Array} array The array to join.
* @param {Array} other The other array to join.
* @returns {Array} Returns the new concatenated array.
*/
function arrayConcat(array, other) {
var index = -1,
length = array.length,
othIndex = -1,
othLength = other.length,
result = Array(length + othLength);
while (++index < length) {
result[index] = array[index];
}
while (++othIndex < othLength) {
result[index++] = other[othIndex];
}
return result;
}
export default arrayConcat;

View File

@@ -1,6 +1,6 @@
/**
* A specialized version of `_.forEach` for arrays without support for callback
* shorthands or `this` binding.
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.

View File

@@ -1,6 +1,6 @@
/**
* A specialized version of `_.forEachRight` for arrays without support for
* callback shorthands or `this` binding.
* callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.

View File

@@ -1,6 +1,6 @@
/**
* A specialized version of `_.every` for arrays without support for callback
* shorthands or `this` binding.
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.

Some files were not shown because too many files have changed in this diff Show More