EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

节点排序 #59

Closed EdwardZZZ closed 4 years ago

EdwardZZZ commented 5 years ago

const newData = [];

function insert(newLayer, layers) {
    const { x: nx, y: ny, width: nwidth, height: nheight } = newLayer;
    if (!layers || layers.length === 0) {
        layers[0] = newLayer;
        return;
    }

    for (let index = 0; index < layers.length; index++) {
        const layer = layers[index];
        const { x, y, width, height } = layer;

        if (x <= nx && x + width >= nx + nwidth
            && y <= ny && y + height >= ny + nheight) {
            if (!layer.children) layer.children = [];
            insert(newLayer, layer.children);
            return;
        }
    }

    layers.push(newLayer);
}

const offset = 20000;
data.sort(({x: x1, y: y1}, {x: x2, y: y2}) => (Math.pow(x1, 2) + Math.pow(y1 + offset, 2)) - (Math.pow(x2, 2) + Math.pow(y2 + offset, 2))).forEach((layer, i) => {
    layer.index = i;
    insert(layer, newData);
});