v1
- by peter-seliger 6/17/202200
Setup HTML - click to add setup HTML
disable setup JavaScript
Setup JavaScript
// flat based and reduce
function flatCallstackCriticalNestedArray_flatBased(arr) {
  while (arr.length < (arr = arr.flat(1000)).length) {
  }
  return arr;
}
function totalNestedNumberValues_flatBasedAndReduce(arr) {
  return flatCallstackCriticalNestedArray_flatBased(arr)
    .reduce((total, value) => (
      'number' === typeof value
        ? total + value
        : total
    ), 0);
}

// stack based and reduce
function flatCallstackCriticalNestedArray_stackBased(nested) {
  const stack = [nested];
  const flat = [];
  let value;

  while (stack.length) {
    if (Array.isArray(value = stack.pop())) {
    
      stack.push(...value);
    } else {
      flat.push(value);
    }
  }
  return flat;
}
function totalNestedNumberValues_stackBasedAndReduce(arr) {
  return flatCallstackCriticalNestedArray_stackBased(arr)
    .reduce((total, value) => (
      'number' === typeof value
        ? total + value
        : total
    ), 0);
}

// stack based and integrated
function totalNestedNumberValues_integratedStack(A) {
  let sum = 0;
  const stack = [A];
  
  while (stack.length > 0) {
    stack.pop().forEach(e => {
      if (Array.isArray(e))
        stack.push(e);
      else if (typeof e === "number")
        sum += e;
    });
  }
  return sum;
}

// Test
const createDeeplyNestedArray = depth => {
  let retval = [1];
  for (let i = 0; i < depth - 1; i++) {
    retval = [1, retval];
  }
  return retval;
};
const NUMBER_OF_ELEMENTS = 100000;
const arr = createDeeplyNestedArray(NUMBER_OF_ELEMENTS);
delete caserun single casemove downdrag and drop case


ready



totalNestedNumberValues_flatBasedAndReduce(arr);
delete caserun single casemove upmove downdrag and drop case


ready



totalNestedNumberValues_stackBasedAndReduce(arr);
delete caserun single casemove updrag and drop case


ready



totalNestedNumberValues_integratedStack(arr);
Test Case - click to add another test case
Teardown JS - click to add teardown JavaScript
Output (DOM) - click to monitor output (DOM) while test is running
RUN