实体引用自身作为下级节点的快速构造

js 生成uuid,递归型实体设置下级实体

var fs = require("fs");
// 生成主键
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

// 生成1000 个最顶级节点,然后为每个节点设置子节点
var res = [];
// 生成1000 个根节点
for (var i = 0; i < 1000; i++) {
    var gid = uuid();
    res.push({
        id: gid,
        name: gid,
        pgid: ''
    });
}

var ress = JSON.parse(JSON.stringify(res));
res = [];

// 生成10000 个二级节点
for (var i = 0; i < 10000; i++) {
    var pgid = ress[Math.floor(Math.random() * 1000)].id;
    var gid = uuid();
    res.push({
        id: gid,
        name: gid,
        pgid: pgid
    });
}

// 生成三级节点
for (var i = 0; i < 1000000; i++) {
    var pgid = res[Math.floor(Math.random() * 10000)].id;
    var gid = uuid();
    res.push({
        id: gid,
        name: gid,
        pgid: pgid
    });
}

var map = {};
var mmm = {};

// 预处理
function predeal(res) {
    for (var i = 0; i < res.length; i++) {
        if (!map[res[i].pgid]) {
            map[res[i].pgid] = [];
        }
        map[res[i].pgid].push(res[i])
    }
}

// 递归设置 实体的下级实体
function dealnode1(root, ress){
    var roots = map[root];
    ress["rrr"] = ress['rrr'] || [];
    ress['rrr'].push(roots);
    for(var i = 0;roots && i < roots.length;i++){
        dealnode1(roots[i].id,roots[i])
    }
}

console.log("开始预处理")
predeal(res);
for (var i = 0; i < ress.length; i++) {
    dealnode1(ress[i].id,ress[i]);
}

console.log("开始输出文件")

fs.writeFile("./nnn.json",JSON.stringify(ress),function(e){
    debugger;
});

你可能感兴趣的:(实体引用自身作为下级节点的快速构造)