Created
June 5, 2018 17:01
-
-
Save PaulGiletich/2e2d554b048e7dd4dcab2f97219aafb2 to your computer and use it in GitHub Desktop.
get intersection of 2 arrays of ranges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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