Skip to content

Commit

Permalink
feat(core): add Point type and distance calculation function
Browse files Browse the repository at this point in the history
Added the Point type, leveraging the Vector2 structure, to represent 2D points in the swiperia-core package. Also implemented a function to calculate the Euclidean distance between two points, complete with unit tests to validate functionality.
  • Loading branch information
samavati committed Apr 13, 2024
1 parent 7f55615 commit 5d90ede
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/swiperia-core/src/lib/point/Point.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { Vector2 } from "../vector2/Vector2.type";

/**
* Represents a 2D point or coordinate.
*/
export type Point = Vector2;
22 changes: 22 additions & 0 deletions packages/swiperia-core/src/lib/point/distance.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Point } from './Point.type';
import { distance } from './distance';

describe('distance', () => {
it('should calculate the distance between two points', () => {
const a: Point = [0, 0];
const b: Point = [3, 4];
expect(distance(a, b)).toEqual(5);
});

it('should handle negative coordinates', () => {
const a: Point = [-2, 3];
const b: Point = [1, -1];
expect(distance(a, b)).toEqual(5);
});

it('should return 0 for the same point', () => {
const a: Point = [5, 5];
const b: Point = [5, 5];
expect(distance(a, b)).toEqual(0);
});
});
16 changes: 16 additions & 0 deletions packages/swiperia-core/src/lib/point/distance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { Point } from './Point.type';

/**
* Calculates the Euclidean distance between two points.
*
* @param a - The first point.
* @param b - The second point.
* @returns The Euclidean distance between the two points.
*/
export const distance = (a: Point, b: Point): number => {
const [ax, ay] = a;
const [bx, by] = b;
const dx = ax - bx;
const dy = ay - by;
return Math.sqrt(dx * dx + dy * dy);
};
2 changes: 2 additions & 0 deletions packages/swiperia-core/src/lib/point/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export type { Point } from './Point.type';
export { distance } from './distance';

0 comments on commit 5d90ede

Please sign in to comment.