Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

flatten - performance improvement #258

Merged
merged 8 commits into from
May 8, 2021
19 changes: 9 additions & 10 deletions packages/array-flatten/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ module.exports = flatten;
*/

function flattenHelper(arr, depth) {
var stack = arr.slice();
var result = [];
var len = arr.length;

for (var i = 0; i < len; i++) {
var elem = arr[i];
while (stack.length) {
var item = stack.pop();

if (Array.isArray(elem) && depth > 0) {
result.push.apply(result, flattenHelper(elem, depth - 1));
if (Array.isArray(item) && depth > 0) {
stack.push.apply(stack, item);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

very nice!

depth--;
} else {
result.push(elem);
result.push(item);
}
}

return result;
return result.reverse();
}

function flatten(arr, depth) {
Expand All @@ -31,7 +32,5 @@ function flatten(arr, depth) {
throw new Error('depth expects a number');
}

var optionDepth = typeof depth === 'number' ? depth : Infinity;

return flattenHelper(arr, optionDepth);
return flattenHelper(arr, typeof depth === 'number' ? depth : Infinity);
}