JSFiddle - React, Tailwind, and code Playground

by Abra Cadabra

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.4/chance.min.js"></script>

JavaScript

var counter = 0;

var w = function(targetObj, pE, stop) {
  var targetHasKids = targetObj && targetObj['items'] && (typeof targetObj['items'].length == 'number' && targetObj['items'].length > 0);

  if (!targetHasKids || stop) {
    targetObj['items'] = [];
    targetObj['items'].push(pE);
    console.log('a push was done!' + (++counter));
  } else {
    var idx = chance.integer({
      min: 0,
      max: targetObj['items'].length - 1
    });

    w(targetObj['items'][idx], pE, chance.bool());
  }
}

var walk = function(source, result, visited) {
  if (!result) {
    result = [];
  }

  var popElem = source.pop();
  popElem['fucked'] = true;

  if (!visited || (chance.bool() && chance.bool())) {
    result.push(popElem);
    console.log('a push was done!' + (++counter));
    visited = true;
  } else {
    var resultArrLength = result.length;
    var dix = chance.integer({
      min: 0,
      max: resultArrLength - 1
    });

    w(result[dix], popElem);
  }

  if (source.length > 0) {
    return walk(source, result, visited);
  } else {
    return result;
  }
};

var i = 10;
var source = [];

while (i--) {
  source.push({
    name: chance.word({
      length: 5
    }) + '_' + i
  });
}

var muia = walk(source);
console.log(muia);