check if point is left or right of line in typescript

To check if a point is on the left or right side of a line in TypeScript, you can use the cross product between the vectors formed by the line segments.

Assuming you have a line defined by two points, (x1, y1) and (x2, y2), and a point (x, y) that you want to check, you can calculate the cross product as follows:

index.ts
function isPointLeftOrRightOfLine(x1: number, y1: number, x2: number, y2: number, x: number, y: number): number {
  // Calculate the cross product of vectors AB and AP
  const crossProduct = (x2 - x1) * (y - y1) - (y2 - y1) * (x - x1);
  
  // The cross product will be positive when the point is to the left of the line
  // The cross product will be negative when the point is to the right of the line
  // The cross product will be zero when the point lies on the line
  if (crossProduct > 0) {
    return 1; // Point is on the left of the line
  } else if (crossProduct < 0) {
    return -1; // Point is on the right of the line
  } else {
    return 0; // Point is on the line
  }
}
688 chars
16 lines

You can call this function passing the coordinates of your line and the point you want to check. It will return 1 if the point is to the left of the line, -1 if it's to the right, and 0 if it lies on the line.

Example usage:

index.ts
const x1 = 0;
const y1 = 0;
const x2 = 2;
const y2 = 2;
const x = 1;
const y = 3;

const result = isPointLeftOrRightOfLine(x1, y1, x2, y2, x, y);
console.log(result); // Output: -1
181 chars
10 lines

In this example, the point (1, 3) is to the right of the line defined by (0, 0) and (2, 2).

related categories

gistlibby LogSnag