ReturnFail

The countDims() function seems to execute right up to the return statement, but then fails to return an actual value.

by Marvin Ward Jr

JavaScript

function constantArray(val,...dim){
  // Function returns an nd-array of the given constant value. Note that the ellipsis in
  // the function definition enables a variable number of arguments. Note that at least one
  // dimension value must be given, and all desired dimension extents must be defined as
  // integer lengths.
  arr_out = [];
  // The initial value forms the kernel of the array
  for (i = 0; i < dim[dim.length - 1]; i++) {
    arr_out.push(val);
  }
  // Reducing the dimension list on each pass provides a natural stopping point for recursion
  dim.pop(dim[dim.length - 1]);
  if (dim.length == 0) {
    return arr_out;
  }
  else {
    // Note that the ellipsis in the function call allows us to pass the remaining dimensions
    // as a list. In this context, the ellipsis is the "spread" operator.
    return constantArray(arr_out, ...dim);
  }
}

function countDims(arr, dim_cnt){
  // Function returns the number of dimensions in an array. Note that we keep the dimension
  // count in the function arguments to ease updating during recursive calls.
    if (dim_cnt == undefined) {dim_cnt = 0};
    if (Array.isArray(arr)) {
    dim_cnt++;
    countDims(arr[0], dim_cnt);
    }
    else {
      console.log("The dimension count of this array is "+dim_cnt);
      console.log("I am in the return space!")
      return dim_cnt;
    }
}

x = constantArray(0, 4, 5)
console.log(x)
x_dims = countDims(x)
console.log(x_dims)