Skip to content

Instantly share code, notes, and snippets.

@PaulGiletich
Created June 5, 2018 17:01
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 PaulGiletich/2e2d554b048e7dd4dcab2f97219aafb2 to your computer and use it in GitHub Desktop.
Save PaulGiletich/2e2d554b048e7dd4dcab2f97219aafb2 to your computer and use it in GitHub Desktop.
get intersection of 2 arrays of ranges
export type Range = [number, number];
export const intersectRangeArrays = (arrA: Range[], arrB: Range[]): Range[] => {
let result = [];
let aLength = arrA.length;
let bLength = arrB.length;
let ai = 0;
let bi = 0;
while (ai < aLength && bi < bLength) {
let a0 = arrA[ai][0];
let a1 = arrA[ai][1];
let b0 = arrB[bi][0];
let b1 = arrB[bi][1];
if (a1 <= b0) {
// a ends before b
ai++;
} else if (b1 <= a0) {
// b ends before a
bi++;
} else {
// a overlaps b
result.push([
a0 > b0 ? a0 : b0,
a1 < b1 ? a1 : b1
]);
// the smaller range is considered processed
if (a1 < b1) {
ai++;
} else {
bi++;
}
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment