flatten<T> method

List<T> flatten <T>(
  1. List arr,
  2. List<T> out
)

Converts a mix of Node and List to List T is Node | MixinArgs (for visitArray commpatibility) arr == [Node, Node, Node...] -> Node, Node, Node, ... MixinArgs don't need to be flatten and don't must be here

Implementation

// List<T> flatten<T>(List<T> arr, List<T> out) {
List<T> flatten<T>(List<dynamic> arr, List<T> out) {
  var _out = out ?? <T>[];

  dynamic item; //Node or List
  int nestedCnt;
  dynamic nestedItem;

  for (var i = 0; i < arr.length; i++) {
    item = arr[i];
    if (item == null) continue;

    if (item is! List) {
      //Node
      _out.add(item);
      continue;
    }

    //item is List
    nestedCnt = (item as List<dynamic>).length;
    for (var j = 0; j < nestedCnt; j++) {
      nestedItem = (item as List<dynamic>)[j];
      if (nestedItem == null) continue;
      if (nestedItem is! List) {
        //Node
        _out.add(nestedItem);
      } else if (nestedItem.isNotEmpty) {
        _out = flatten<T>(nestedItem, _out);
      }
    }
  }

  return _out;

//2.3.1
//  flatten: function(arr, out) {
//      if (!out) {
//          out = [];
//      }
//
//      var cnt, i, item,
//          nestedCnt, j, nestedItem;
//
//      for (i = 0, cnt = arr.length; i < cnt; i++) {
//          item = arr[i];
//          if (item === undefined) {
//              continue;
//          }
//          if (!item.splice) {
//              out.push(item);
//              continue;
//          }
//
//          for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
//              nestedItem = item[j];
//              if (nestedItem === undefined) {
//                  continue;
//              }
//              if (!nestedItem.splice) {
//                  out.push(nestedItem);
//              } else if (nestedItem.length) {
//                  this.flatten(nestedItem, out);
//              }
//          }
//      }
//
//      return out;
//  }
}