Trying to create a function mCreate()
that given a set a numbers returns a multidimensional array (matrix):
mCreate(2, 2, 2)
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
When this functions handles just 2 levels of depth ie: mCreate(2, 2) //[[0, 0], [0, 0]]
I know to do 2 levels, you can use 2 nested for loops
but the problem I'm having is how to handle an n'th number of arguments.
Would this problem be better approached with recursion, otherwise how can I dynamically determine the number of nested for loops
I'm going to need given the number of arguments?
ps: the most performant way would be great but not essential
RE-EDIT - After using Benchmark.js to check perf the results were as follows:
BenLesh x 82,043 ops/sec ±2.56% (83 runs sampled)
Phil-P x 205,852 ops/sec ±2.01% (81 runs sampled)
Brian x 252,508 ops/sec ±1.17% (89 runs sampled)
Rick-H x 287,988 ops/sec ±1.25% (82 runs sampled)
Rodney-R x 97,930 ops/sec ±1.67% (81 runs sampled)
Fastest is Rick-H
@briancavalier also came up with a good solution JSbin:
const mCreate = (...sizes) => (initialValue) => _mCreate(sizes, initialValue, sizes.length-1, 0)
const _mCreate = (sizes, initialValue, len, index) =>
Array.from({ length: sizes[index] }, () =>
index === len ? initialValue : _mCreate(sizes, initialValue, len, index+1))
mCreate(2, 2, 2)(0)