TestsPerf

4 years ago
User agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36
Test name Executions per second
@john36allTa 191.8 Ops/sec
@dimoff66 116.1 Ops/sec
@Bavashi 90.9 Ops/sec
Script Preparation code:
x
 
var arr = [];
var len = 1000;
function init() {
for (var i = 0; i < len; i++) {
    arr.push({
        id: i+1,
        name: i+" ...",
        parent: i
    });
}}
init();
Tests:
  • @john36allTa

     
    function pack( data ){
      const childs = id => 
        data.filter( item => item.parent === id )
          .map( 
            ({id,name}) => ({id,name, children: childs(id)}) 
          ).map(
            ({id,name,children}) => children.length ? {id,name, children} : { id, name }
          );
      return childs(0);
    }
    const res = pack(arr)
  • @dimoff66

     
    function pack( arr ) {
      const map = Object.assign({} , ...arr.map(v => 
        ({ [v.id]: Object.assign(v, { children: [] }) })
      ))
      const tree = Object.values(map).filter(v => 
       !(v.parent && map[v.parent].children.push(v))
      )
      
      return tree
    }
    const res = pack(arr)
  • @Bavashi

     
    function makeTree(array, parent) {
      var tree = {};
      parent = typeof parent !== 'undefined' ? parent : {id: 0};
      var childrenArr = array.filter(function(child) {
        return child.parent == parent.id;
      });
      if (childrenArr.length > 0) {
        var childrenObj = {};
        childrenArr.forEach(function(child) {
          childrenObj[child.id] = child;
        });
        if (parent.id == 0) {
          tree = childrenObj;
        } else {
          parent.children = childrenObj;
        }
        childrenArr.forEach(function(child) {
          makeTree(array, child);
        })
      }
      return tree;
    };
    const res = makeTree(arr);
Open this result on MeasureThat.net