loading...

re: How do you write an empty array? VIEW POST

FULL DISCUSSION
 

If the challenge/problem specified the cardinality of the sets each of the dimensions span, we could use a recursive function, something like:

type Space<T> = T | Array<Space<T>>

function initSpace<T>(identity: T, ...cardinalities: number[]): Space<T> {
  if (!cardinalities.length) return identity

  let cardinality = cardinalities[0]
  cardinalities = cardinalities.slice(1)

  return new Array(cardinality)
    .fill(null)
    .map(() => initSpace(identity, ...cardinalities))
}

Let's say you want that three-dimensional array to be Rubik's cube-like, filled with zeros:

let numbers: Space<number> = initSpace<number>(0, 3, 3, 3)

Otherwise, I'd simply go for the solution @wingkwong posted: [] 🤷‍♂️

Code of Conduct Report abuse