Looking to flatten an array of 1D arrays and simple elements, reporting all combinations until reaching a leaf "node." For example:
// Given input array with single elements or 1D arrays:
let input = [1, 2, [3, 4], [5, 6]];
The unfolding process splits paths for each encountered array into as many elements as the array contains:
// current result = [1, 2]
// remaining input [[3, 4], [5, 6]]
// ->
// current result = [ [1, 2, 3], [1, 2, 4] ]
// current result = [ [1, 2, 3], [1, 2, 4] ]
// remaining input [[5, 6]]
// ->
// final result = [ [1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 3, 6], [1, 2, 4, 6] ]
Struggling with handling special cases like:
let input1 = [1, 2, 3]; // No nested arrays
let input2 = []; // Empty input
Attempted to build the result backwards using .pop
, but facing issues with typescript compilation:
function flatPath(input, result = [[]]) {
while (input.length) {
const last = input.pop();
if (Array.isArray(last)) {
result = flatPath(last, [...result, ...result]);
} else {
for (let ar of result) {
result.push(last);
}
}
}
return result;
}
let result = flatPath([1, 2, [3, 4], [2, 5, 6] ]);
console.log(result);
Encountering errors like 'Parameter 'input' implicitly has an 'any' type' and 'Argument of type 'any' is not assignable to parameter of type 'never'.
Is there a better way to achieve this or can you help identify the issue in my code?