Optimize baseFlatten.

This commit is contained in:
jdalton
2015-05-29 11:26:14 -04:00
parent f69715d999
commit 9c339367ad

View File

@@ -2031,13 +2031,15 @@
* @param {Array} array The array to flatten. * @param {Array} array The array to flatten.
* @param {boolean} [isDeep] Specify a deep flatten. * @param {boolean} [isDeep] Specify a deep flatten.
* @param {boolean} [isStrict] Restrict flattening to arrays-like objects. * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array. * @returns {Array} Returns the new flattened array.
*/ */
function baseFlatten(array, isDeep, isStrict) { function baseFlatten(array, isDeep, isStrict, result) {
result || (result = []);
var index = -1, var index = -1,
length = array.length, length = array.length,
resIndex = -1, resIndex = result.length - 1;
result = [];
while (++index < length) { while (++index < length) {
var value = array[index]; var value = array[index];
@@ -2045,13 +2047,14 @@
(isStrict || isArray(value) || isArguments(value))) { (isStrict || isArray(value) || isArguments(value))) {
if (isDeep) { if (isDeep) {
// Recursively flatten arrays (susceptible to call stack limits). // Recursively flatten arrays (susceptible to call stack limits).
value = baseFlatten(value, isDeep, isStrict); baseFlatten(value, isDeep, isStrict, result);
} } else {
var valIndex = -1, var valIndex = -1,
valLength = value.length; valLength = value.length;
while (++valIndex < valLength) { while (++valIndex < valLength) {
result[++resIndex] = value[valIndex]; result[++resIndex] = value[valIndex];
}
} }
} else if (!isStrict) { } else if (!isStrict) {
result[++resIndex] = value; result[++resIndex] = value;