3

I'm working some JS algorithms with TS. So I made this functions:

function steamrollArray(arr: any[]): any[] {
  return arr.reduce(
    (accum: any, val: any) =>
      Array.isArray(val) ? accum.concat(steamrollArray(val)) : accum.concat(val)
  , []);
}

but the arguments need the flexibility to accept multiple dimension arrays, as follow:

steamrollArray([[["a"]], [["b"]]]);
steamrollArray([1, [2], [3, [[4]]]]);
steamrollArray([1, [], [3, [[4]]]]);
steamrollArray([1, {}, [3, [[4]]]]);

Which is the proper way to define the arguments for the function?

Certainly I could use Types, like here: typescript multidimensional array with different types but won't work with all cases.

1 Answer 1

1

You'll want to define a type that is possibly an array and possibly not. Something like:

type MaybeArray<T> = T | T[];

Then you can update your function to:

function steamrollArray<T>(arr: MaybeArray<T>[]): T[] {
    return arr.reduce(
        (accum: any, val: any) =>
             Array.isArray(val) ? accum.concat(steamrollArray(val)) : accum.concat(val)
    , []);
}

With that, Typescript will be able to parse the types correctly and understand your intent.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. Your method works for most cases, except the last one which includes {}. Had to add {} in the type. accum can be defines with T[] but val can't, not even MaybeArray<T>[].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.