Skip to content

Commit

Permalink
flatten - performance improvement (#258)
Browse files Browse the repository at this point in the history
* implement cancel method to throttle

* flat array using iterative solution

Co-authored-by: angus croll <[email protected]>
  • Loading branch information
EvandroLG and angus-c authored May 8, 2021
1 parent 79f875a commit 707f0ac
Showing 1 changed file with 9 additions and 10 deletions.
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);
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);
}

0 comments on commit 707f0ac

Please sign in to comment.