впрочем я вижу у вас претензии ко всему миру?
<button onclick="startTest()">Запустить тесты</button>
<script>
const rnd = (min, max) => {
let rand = min + Math.random() * (max + 1 - min)
return Math.floor(rand)
}
const init = (len) => {
const arr = [
{ id: 1, name: 'root', parent: 0 },
{ id: 2, name: '2', parent: 1 },
{ id: 3, name: '3', parent: 1 },
{ id: 4, name: '4', parent: 1 },
{ id: 5, name: '5', parent: 2 },
{ id: 6, name: '6', parent: 2 },
{ id: 7, name: '7', parent: 3 },
{ id: 8, name: '8', parent: 4 },
]
for (let i = 8; i < len; i++)
arr.push({ id: i+1, name: i+" ...", parent: rnd(5, 8) })
return arr
}
function test1( 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);
}
function test2( 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
}
function test3(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) {
test3(array, child);
})
}
return tree;
};
function startTest () {
const fns = [[test1, "@john36allTa"], [test2, "@dimoff66"], [test3, "@Bavashi"]]
const counts = [[500, 400], [1000, 200], [2000, 100], [5000, 50]]
counts.forEach(v => {
const [len, cnt] = v
console.log("Размер:" + len + ", повторить:" + cnt + " раз")
const data = init(len)
fns.forEach((v, ind) => {
const [fn, name] = v
console.time(name)
for (let i = 0; i < cnt; i++) fn(data)
console.timeEnd(name)
})
console.log("------------------------")
})
}
</script>