Skip to content

Instantly share code, notes, and snippets.

@demurgos
Created October 2, 2018 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save demurgos/5768ec3f26c0ce10b874031f09af00dc to your computer and use it in GitHub Desktop.
Save demurgos/5768ec3f26c0ce10b874031f09af00dc to your computer and use it in GitHub Desktop.
function fromSortedRanges(ranges: ReadonlyArray<RangeCov>): RangeTree | undefined {
let root: RangeTree | undefined;
const stack: RangeTree[] = [];
for (const range of ranges) {
const node: RangeTree = new RangeTree(range.startOffset, range.endOffset, range.count, [], 0, 0);
if (root === undefined) {
root = node;
stack.push(node);
continue;
}
let top: RangeTree;
while (true) {
top = stack[stack.length - 1];
// assert: `top !== undefined` (the ranges are sorted)
if (range.startOffset < top.end) {
break;
} else {
stack.pop();
}
}
top.children.push(node);
stack.push(node);
}
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment