Skip to content
Merged
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Copy Markdown
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);
}