'use strict';

var map = require('../lib/map').map;
var pretty = require('../lib/utils').pretty;

function Tree(parent, children, data) {
  this.parent = parent || null;
  this.children = [].concat(children || []);
  this.data = data;
}

Object.defineProperties(Tree.prototype, {
  bfsForEach: {value: bfsForEach}
})

function bfsForEach(cb) {
  var level = [this];

  while (level.length) {
    cb(level);
    level = level.reduce(function(nextLevel, t) {
      return nextLevel.concat(t.children);
    }, []);
  }
}

function treeFactory(parent, children, data) {
  return new Tree(parent, children, data);
}

var schema = [{
    type: 'record',
    name: 'A',
    fields: [{
      name: 'A1', type: 'string'
    }, {
      name: 'A2', type: 'int'
    }]
}, {
    type: 'record',
    name: 'B',
    fields: [{
      name: 'B1', type: [null, 'int', 'A']
    }, {
      name: 'B2', type: {type: 'array', items: 'string'}
    }]
}];
var schemaTrees = map(schema, function(parent, entry, keyChain) {
    var t = treeFactory(parent, null, {
      path: keyChain.join('.'),
      type: entry.type
    });

    ((parent || {}).children || []).push(t);

    return t;
});

schemaTrees[schemaTrees.length - 1].bfsForEach(function(level) {
  console.log(level.map(function(t) {
    return t.data.path;
  }).join(', ') + '\n');
})

@@ -278,23 +278,22 @@
  %7B%0A  bfs
-ForEach
+Reduce
 : %7Bvalue
@@ -301,43 +301,86 @@
  bfs
-ForEach%7D%0A%7D)%0A%0Afunction bfsForEach(cb
+Reduce%7D,%0A  toString: %7Bvalue: toString%7D%0A%7D)%0A%0Afunction bfsReduce(cb, initialValue
 ) %7B%0A
@@ -435,11 +435,40 @@
     
-cb(
+initialValue = cb(initialValue, 
 leve
@@ -579,16 +579,248 @@
 %5B%5D);%0A  %7D
+%0A%0A  return initialValue;%0A%7D%0A%0Afunction toString() %7B%0A  return this.bfsReduce(function(result, level) %7B%0A    return result.concat(%0A      level.map(function(t) %7B%0A        return t.data.path;%0A      %7D).join(' %7C ')%0A    );%0A  %7D, %5B%5D).join('%5Cn');
 %0A%7D%0A%0Afunc
@@ -1364,16 +1364,26 @@
 oin('.')
+ %7C%7C 'ROOT'
 ,%0A      
@@ -1473,16 +1473,28 @@
 t;%0A%7D);%0A%0A
+console.log(
 schemaTr
@@ -1525,123 +1525,17 @@
  1%5D.
-bfsForEach(function(level) %7B%0A  console.log(level.map(function(t) %7B%0A    return t.data.path;%0A  %7D).join(', ') + '%5Cn');%0A%7D)
+toString());
 %0A

update example