Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Last active December 5, 2021 12:35
Show Gist options
  • Save steveruizok/1763a2240b603d76051229a4eb02b871 to your computer and use it in GitHub Desktop.
Save steveruizok/1763a2240b603d76051229a4eb02b871 to your computer and use it in GitHub Desktop.
Get the intersection point, if any, between two infinite lines.
export function intersectLineLine(AB: number[][], PQ: number[][]): number[] | undefined {
const slopeAB = AB[0][0] === AB[1][0] ? NaN : (AB[0][1] - AB[1][1]) / (AB[0][0] - AB[1][0])
const slopePQ = AB[0][0] === PQ[1][0] ? NaN : (PQ[0][1] - PQ[1][1]) / (PQ[0][0] - PQ[1][0])
if (slopeAB === slopePQ) return undefined
if (Number.isNaN(slopeAB) && !Number.isNaN(slopePQ)) {
return [AB[0][0], (AB[0][0] - PQ[0][0]) * slopePQ + PQ[0][1]]
}
if (Number.isNaN(slopePQ) && !Number.isNaN(slopeAB)) {
return [PQ[0][0], (PQ[0][0] - AB[0][0]) * slopeAB + AB[0][1]]
}
const x = (slopeAB * AB[0][0] - slopePQ * PQ[0][0] + PQ[0][1] - AB[0][1]) / (slopeAB - slopePQ)
const y = slopePQ * (x - PQ[0][0]) + PQ[0][1]
return [x, y]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment