function c (arr) {
var ids = [],
result = [],
randomKey = Math.random().toString(32).slice(-8),
map = new Map();
function createItem (name, index) {
ids.length = index + 1;
ids[index] = (ids[index] || 0) + 1;
let cl = ids.slice(0, index + 1).map(k => String(k).padStart(2, '0')).join('');
return {
name,
id: cl
};
}
function add(list) {
let base,
vk = [];
list.forEach((o, i) => {
vk.push(o);
let d = vk.join(randomKey),
mo;
if (!map.has(d)) {
mo = createItem(o, i);
map.set(d, mo);
if (base) {
base.child = (base.child || []).concat(mo);
} else {
result.push(mo);
}
} else {
mo = map.get(d);
}
base = mo;
});
}
arr.forEach(k => add(k));
return result;
}
var t = [['hello','bil'],['hello','jack'],['world','foo','jerry'],['world','foo','peter','tom'],['world','bar']];
var result = c(t);
JSON.stringify(result, null, 4);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…