find the distance between two points in typescript

To find the distance between two points in TypeScript, you can use the following formula that calculates the Euclidean distance between two points in a two-dimensional plane:

index.ts
function getDistance(x1: number, y1: number, x2: number, y2: number): number {
  const xDistance = x2 - x1;
  const yDistance = y2 - y1;
  return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
}
208 chars
6 lines

This function takes four parameters, which are the x and y coordinates of the two points, and returns the distance between them. The Math.sqrt() function calculates the square root of the sum of the squares of the x and y distances, and returns the distance between the two points.

Here is an example usage of the function:

index.ts
const point1X = 10;
const point1Y = 5;
const point2X = 20;
const point2Y = 15;

const distance = getDistance(point1X, point1Y, point2X, point2Y);
console.log(distance); // Output: 14.142135623730951
199 chars
8 lines

This will output the distance between the two points (10, 5) and (20, 15), which is approximately 14.14 units.

gistlibby LogSnag