in packages/core/micro/src/adjust-tree/node.ts [223:260]
export function ensureBalancedChildInNode<T>(ctx: TreeContext<T>, parent: InteriorNode<T>, childIndex: number): Orphan<T> | undefined {
const size = parent.size;
const { segments } = parent;
const child = segments[childIndex]
if (child.size >= ctx.order) {
return undefined;
}
if (size < 2) {
return { node: child, heightDelta: 1, length: parent.lengths[childIndex] };
}
let leftIndex;
let rightIndex;
if (childIndex === 0) {
leftIndex = 0;
rightIndex = 1;
} else {
leftIndex = childIndex - 1;
rightIndex = childIndex;
}
const rhs = segments[rightIndex];
// Cast here is just to guarantee that both nodes are of the same
// kind. We don't care whether they are interior or leaf nodes.
const balancing = rebalanceNodes(ctx, segments[leftIndex] as InteriorNode<T>, rhs as InteriorNode<T>);
if (balancing === 0) {
return undefined;
}
const { lengths } = parent;
if (rhs.size === 0) {
lengths[leftIndex] += balancing;
assert("ensureBalancedChildInNode - deleting right should return a delta equal to rhs len ", balancing === lengths[rightIndex]);
deleteNodeRange(parent, rightIndex, 1, undefined!);
return undefined;
}
lengths[leftIndex] += balancing;
lengths[rightIndex] -= balancing;
return undefined;
}