check if point is left or right of line or above or below in typescript

To determine if a point is left or right of a line, or above or below the line, you can use the concept of cross product in geometry.

Here's how you can do it in TypeScript:

index.ts
interface Point {
  x: number;
  y: number;
}

interface Line {
  start: Point;
  end: Point;
}

function isPointLeftOfLine(point: Point, line: Line): boolean {
  return (
    (line.end.x - line.start.x) * (point.y - line.start.y) -
    (line.end.y - line.start.y) * (point.x - line.start.x)
  ) > 0;
}

function isPointRightOfLine(point: Point, line: Line): boolean {
  return (
    (line.end.x - line.start.x) * (point.y - line.start.y) -
    (line.end.y - line.start.y) * (point.x - line.start.x)
  ) < 0;
}

function isPointAboveLine(point: Point, line: Line): boolean {
  return (
    (line.end.y - line.start.y) * (point.x - line.start.x) -
    (line.end.x - line.start.x) * (point.y - line.start.y)
  ) > 0;
}

function isPointBelowLine(point: Point, line: Line): boolean {
  return (
    (line.end.y - line.start.y) * (point.x - line.start.x) -
    (line.end.x - line.start.x) * (point.y - line.start.y)
  ) < 0;
}
923 chars
38 lines

You can use these functions by providing a Point and a Line object. The functions will return true if the point is on the specified side of the line, and false otherwise.

Note that these functions assume that the line is defined by two distinct points start and end.

Here's an example usage:

index.ts
const point: Point = { x: 1, y: 1 };
const line: Line = { start: { x: 0, y: 0 }, end: { x: 2, y: 2 } };

console.log(isPointLeftOfLine(point, line));  // Output: false
console.log(isPointRightOfLine(point, line)); // Output: false
console.log(isPointAboveLine(point, line));   // Output: false
console.log(isPointBelowLine(point, line));   // Output: false
357 chars
8 lines

In this example, the point is on the line, so all the functions return false. Depending on the coordinates of the point and line, the functions will return the appropriate results.

Remember to replace Point and Line with your own data structures if you have defined them differently.

related categories

gistlibby LogSnag