Find the intersection of two lines

func det(a, b, c, d) { a*d - b*c }
 
func intersection(ax, ay, bx, by,
                  cx, cy, dx, dy) {
 
    var detAB = det(ax,ay, bx,by)
    var detCD = det(cx,cy, dx,dy)
 
    var ΔxAB = (ax - bx)
    var ΔyAB = (ay - by)
    var ΔxCD = (cx - dx)
    var ΔyCD = (cy - dy)
 
    var x_numerator = det(detAB, ΔxAB, detCD, ΔxCD)
    var y_numerator = det(detAB, ΔyAB, detCD, ΔyCD)
    var denominator = det( ΔxAB, ΔyAB,  ΔxCD, ΔyCD)
 
    denominator == 0 && return 'lines are parallel'
    [x_numerator / denominator, y_numerator / denominator]
}
 
say ('Intersection point: ', intersection(4,0, 6,10, 0,3, 10,7))
say ('Intersection point: ', intersection(4,0, 6,10, 0,3, 10,7.1))
say ('Intersection point: ', intersection(0,0, 1,1, 1,2, 4,5))

Output:

Intersection point: [5, 5]
Intersection point: [2300/459, 2320/459]
Intersection point: lines are parallel

Last updated