From 0a4eda37ee4adf9c278281212ed74c3dde31cf02 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 3 Jun 2023 21:23:26 +0200 Subject: [PATCH] =?UTF-8?q?problems(js):=20add=20=E2=80=9C2625.=20Flatten?= =?UTF-8?q?=20Deeply=20Nested=20Array=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/js/flatten-deeply-nested-array.js | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 problems/js/flatten-deeply-nested-array.js diff --git a/problems/js/flatten-deeply-nested-array.js b/problems/js/flatten-deeply-nested-array.js new file mode 100644 index 0000000..151d6d7 --- /dev/null +++ b/problems/js/flatten-deeply-nested-array.js @@ -0,0 +1,34 @@ +/** + * @param {any[]} arr + * @param {number} depth + * @return {any[]} + */ +var flat = function (arr, n) { + let stack = [[arr, 0, 0]]; + + let flattened = []; + while (stack.length) { + let [arr, depth, i] = stack.pop(); + if (i >= arr.length) { + // finished with the nested array + continue; + } + + // if it's a nested array and not deep enough + if (depth < n && arr[i] instanceof Array) { + // gotta continue with the next element of the array + stack.push([arr, depth, i + 1]); + + // gotta start with the first element of the nested + stack.push([arr[i], depth + 1, 0]); + + // yielding is done only on the elements themselves + continue; + } + + flattened.push(arr[i]); + stack.push([arr, depth, i + 1]); + } + + return flattened; +};