var formatCollection = (function () {
function findNode(id, data) {
for (var index = 0; index < data.length; index++) {
if (data[index].id == id) {
return data[index].children;
} else {
var children = data[index].children;
var node = findNode(id, children);
if (node) {
return node;
}
}
}
}
function makeCollection(nodes, results) {
nodes = _.sortBy(nodes, function (node) {
return node['item'].position;
});
_.forEach(nodes, function (node) {
results.push(node.item);
makeCollection(node.children, results);
});
}
return function (collection) {
var data = [
{
id: 0,
children: []
}
];
while (collection.length > 0) {
var item = collection.shift();
var node = findNode(item.parentId || 0, data);
if (node) {
node.push({
id: item.id,
item: item,
children: []
});
} else {
collection.push(item);
}
}
var formattedCollection = [];
makeCollection(data[0].children, formattedCollection);
return formattedCollection;
};
})();