From 707f0ac693427e1778aa4b3ffa44fea00c40002b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Evandro=20Leopoldino=20Gon=C3=A7alves?= Date: Sat, 8 May 2021 07:58:56 +0200 Subject: [PATCH] flatten - performance improvement (#258) * implement cancel method to throttle * flat array using iterative solution Co-authored-by: angus croll --- packages/array-flatten/index.js | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/packages/array-flatten/index.js b/packages/array-flatten/index.js index 7610b4f69..78f053369 100644 --- a/packages/array-flatten/index.js +++ b/packages/array-flatten/index.js @@ -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) { @@ -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); }