The Array.prototype.flat () method of the array, how to use tail recursion to achieve it?

The

Array.prototype.flat () method can flatten the nested array into flattening into one-dimensional array , accept a number as several layers of expansion, and defaults to layer 1 . If you expand no matter how many layers are nested, you can pass in a Infinity .

function g1() {
    return 1
}
function fn1() {
    return g1()
}

fn1 function calls another function in the last step G1

The

function calls itself, which is called recursion. If the tail calls itself, it is called tail recursion. so the question is, how do you use tail recursion to optimize the above recursive function?

I"m a little stupid. I can"t figure it out for the time being. So please share your thoughts

.

problem description

the environmental background of the problems and what methods you have tried

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?

Sep.16,2021


, ,

let time = 0
function flat(arr) {
  if (arr.length === 0 || !Array.isArray(arr)) return;
  let containsArray = false;

  for (let i = 0; i < arr.length; iPP) {
    if (Array.isArray(arr[i])) {
      containsArray = true;
      let before = arr.slice(0, i);
      let after = arr.slice(i + 1);
      arr = before.concat(arr[i]).concat(after)
      break;
    }
  }
  console.log(PPtime)
  return containsArray ? flat(arr) : arr;
}

flat([1, 2, [3, 4, 5, [6], [7]], 8, [9], [10], [11, [12]]]

Last print: 8 executed 8 times

Menu