JSFiddle - React, Tailwind, and code Playground

by rap1ds

HTML

<h2>iterativeWalkTree:</h2>
<div id="iterativeWalkTree"></div>
<h2>asyncIterativeWalkTree:</h2>
<div id="asyncIterativeWalkTree"></div>

CSS

h2 {
    font-size: 20px;   
}

JavaScript

var tree, resultElement, char;

function createTree(nodes, maxChildren) {
    var root = {index: nodes, children: []};
    nodes--;
    var queue = [root];
    while (nodes) {
        var parentIdx = Math.floor(Math.random() * queue.length),
            parent = queue.splice(parentIdx, 1)[0],
            minChildren = queue.length > 0 ? 0 : 1;
            children = minChildren + 
                Math.floor(Math.random() * (1 + maxChildren));
        
        while(parent && children && nodes) {
            var child = {index: nodes, children: []};
            nodes--;
            children--;
            parent.children.push(child);
            queue.push(child); // Add child    
        }
    }
    return root;
}

function pause(ms) {
    var endTime = (new Date()).getTime() + ms;
    do {  
        // Do nothing
    } while(endTime > (new Date()).getTime());  
}


function doSomethingWith(n) {
    pause(50);
    resultElement.append('.');
    if(char > 50) {
        resultElement.append('<br />');
        char = 0;
    }
}

function iterativeWalkTree(node) {
    var queue = [node];
    while (queue.length) {
        var n = queue.shift();
        for (var i = 0; i < n.children.length; i++) {
            queue.push(n.children[i]);
        }
        doSomethingWith(n);
    }
}
    
function asyncIterativeWalkTree(node) {
    var queue = [node];

    var processQueue = function() {
        var n = queue.shift();
        for (var i = 0; i < n.children.length; i++) {
            queue.push(n.children[i]);
            setTimeout(processQueue, 0);
        }
        doSomethingWith(n);
    }

    processQueue();
}

char = 0;
resultElement = $('#iterativeWalkTree');
tree = createTree(50, 10);
iterativeWalkTree(tree);

char = 0;
resultElement = $('#asyncIterativeWalkTree');
tree = createTree(50, 10);
asyncIterativeWalkTree(tree);