/* Write some code, that will flatten an array of arbitrarily
nested arrays of integers into a flat array of integers.
e.g. [[1,2,[3]],4] -> [1,2,3,4]. */


const flattenArray = array => array.reduce(
  (acumulator, element) => acumulator.concat(
    Array.isArray(element) ?
      flattenArray(element)
      :
      element
  ), []
)

/* I'm sure that your team have amazing engineers that  
understand the recursivity and functional javascript + es6.
But for the rest of humans, I can explicate it:*/

function flattenArrayForDommies(array) {
  // first, I'm using the array method reduce. this let me iterate 
  // every item and get an acumulator. We define a the method for generate
  // this acumulator
  console.log("recursive itself:" array);
  return array.reduce(iterate, []);
}

// reduce method
function iterate(acumulator, element) {
  console.log("current acum:", acumulator);
  console.log("current element:", element);
  // if the element is an array, call recursive flatten array method 
  if (Array.isArray(el)) {
    // if is an array, return the acumulator concat with the recursive call
    // for the array element
    return [...acum, ...(flattenArrayForDommies(el))]; // spread operator :D
  }
  // if it is not an array, push it in the acumulator
  return [...acum, (el)];
}

console.log("flatten", flattenArray([[1,2,[3]],4]))
console.log("flatten", flattenArrayForDommies([[1,2,[3]],4]))