"Steamroller" is this a good enough solution?

I might be taking shortcut here
So, the code bellow used to not have the last line, and used to fail all tests because the result array used to already contain items because of:

steamrollArray([1, [2], [3, [[4]]]]);

Now my code works just fine if I delete this line or add my shortcut solution of resetting the array back to empty.
So my question is does this code count as a pass?
I tried to cut out pushing items into an array and it resulted in a fail (filtered array somehow still had arrays in them).
I would appreciate your ideas of what would had worked instead of:

result.push(i)

  **Your code so far**

const result = [];
function steamrollArray(arr) {
arr.filter(i => !Array.isArray(i)?result.push(i):
steamrollArray(i)
)
return  result
}

steamrollArray([1, [2], [3, [[4]]]]);
result.length = 0;
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36

Challenge: Steamroller

Link to the challenge:

Generally using external array will make it hard to re-use the function. What kind of defeats the purpose of function.

Because function mutates result array, each further execution of steamrollArray will not start with empty array, but with side-effects of the previous run.

Relatively easy, your current code can be wrapped into function that will keep result array isolated from other runs, for example:

function steamrollArray(arr) {
  function mutatingResult(arr) {
    /*  */
  }
  const result = [];
  mutatingResult(arr);
  return result;
}

Where mutatingResult is really your current function.

That’s one option without changing much in the function. On the other hand some closer look may change some of the internal logic, to make it more predictable. For a start, consider what filter is doing here. Remember that filter filters items, and returns new array, depending on the result of the callback function. However that might not be an intention here, after all, all elements are needed, just maybe flattened or not. From that description, more standard iterating over the array might be worth considering.

Thank you for your suggestions sanity,
creating recursive function inside steamrollArray(arr) scope did work.
Now when you are saying:

are you referring to another pure function or a totally different approach?

The inner ‘faux-recursion’ approach works but isn’t my favorite. That’s basically an obfuscated while loop. I’d try converting to a loop or use true recursion that uses the return value of the function call.

Just a normal for loop would be a good starting point.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.