function (tree) { // http://programmers.stackexchange.com/questions/214227/ var stack = [], replies = tree.replies.slice(1, tree.replies.length), root = tree.replies[0]; root.children = []; stack.push(root); replies.forEach(function (reply) { var delta = reply.depth - stack.length; reply.children = []; if (delta > 0) { assert(delta === 1); stack.push(stack.front().children.front()); } while (delta < 0) { stack.pop(); delta++; } stack.front().children.push(reply); }); this.rootReply = root; },