atool-vip / comments

0 stars 0 forks source link

perf/ #19

Open utterances-bot opened 3 months ago

utterances-bot commented 3 months ago

JavaScript benchmark 性能对比 · 一个工具 - VIP

在线 jsperf 工具,可以对比多个 JS 代码片段的 perf benchmark 性能数据,选择性能最高的写法!

https://atool.vip/perf/

fanjizeng commented 3 months ago

function buildTree(A, B) { // 创建一个 id 到 parent 对象的映射 const map = new Map();

// 初始化 map A.forEach(item => { map.set(item.id, { ...item, children: [] }); });

// 遍历 B 数组,将子项添加到对应的父项的 children 数组中 B.forEach(item => { const parent = map.get(item.pid); if (parent) { parent.children.push(item); } });

// 将 map 的 values 转换为数组并返回 return Array.from(map.values()); }

// 示例数据 const A = [ { id: 1, name: 'Parent 1' }, { id: 2, name: 'Parent 2' } ];

const B = [ { pid: 1, name: 'Child 1-1' }, { pid: 1, name: 'Child 1-2' }, { pid: 2, name: 'Child 2-1' } ];

// 构建树对象 const tree = buildTree(A, B);

console.log(JSON.stringify(tree, null, 2));