function reparent()

in packages/core/micro/src/adjust-tree/delete.ts [37:75]


function reparent<T>(ctx: TreeContext<T>, node: AdjustNode<T>, orphan: Orphan<T>, before: boolean): Insertion<T> {
    const { heightDelta, node: child, length } = orphan;
    const idx = before ? 0 : node.size - 1;
    assert("We can only call reparent on interior nodes", node.kind === NodeKind.Interior);
    if (heightDelta > 1) {
        orphan.heightDelta--;
        return applyInsertion(ctx, node, idx, length, reparent(ctx, node.segments[idx], orphan, before));
    }

    const sibling = node.segments[idx];
    const siblingLen = node.lengths[idx];

    const lenChange = before
        ? rebalanceNodes(ctx, child as InteriorNode<T>, sibling as InteriorNode<T>)
        : rebalanceNodes(ctx, sibling as InteriorNode<T>, child as InteriorNode<T>);

    if (lenChange === 0) {
        return insertChild(ctx, node, child, length, before ? 0 : node.size);
    }

    if (child.size === 0) {
        node.lengths[idx] += length;
        return undefined;
    }

    if (before) {
        if (sibling.size === 0) {
            node.lengths[idx] += length;
            node.segments[idx] = child;
            return undefined;
        }
        node.lengths[idx] = siblingLen - lenChange;
        const res = insertChild(ctx, node, child, length + lenChange, /* index */ 0);
        return res;
    }

    node.lengths[idx] += lenChange;
    return insertChild(ctx, node, child, length - lenChange, /* index */ node.size);
}