File folder things (v2)

Revision 2 of this benchmark created on


Setup

 function getFlatArr(folderCount, fileCount){
    let arr = [];

    for (let i = 0; i <= folderCount; i++) arr.push({
      name: 'folder'+i, type: 'folder', parent: (arr[Math.floor(Math.random()*arr.length)]?.name || 'root')
    });

    for (let i = 0; i <= fileCount; i++) arr.push({
      name: 'file'+i, type: 'file', parent: arr[Math.floor(Math.random()*folderCount)]?.name || 'root'
    });

    return arr;
  }
  
  const flatArray = getFlatArr(10, 10)

Test runner

Ready to run.

Testing in
TestOps/sec
recursive
function format(ar,root={name:'root', children:[]}){
  root.children = root.children || [];

  for(let n of ar) {
    if(n.parent === root.name) {
      root.children.push(n);
      if(n.type === 'folder') format(ar,n);
    }
  }
  return root;
}

format(flatArray);
ready
mapping
function format( flatArray ) {
  
  const root = { name: 'root', type: 'folder', children: [] };
  const map = {};

  for (let item of flatArray) {
  	if (item.type === 'folder') item.children = [];
  	map[item.name] = item;
  }

  for (let item of flatArray) {
      if (map[item.parent]) map[item.parent].children.push(map[item.name]);
      else root.children.push(map[item.name]);
  };

  return root;
  
}

format(flatArray);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.