Skip to content

Commit

Permalink
convert coord to typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
n-peugnet committed Apr 20, 2019
1 parent d643caa commit 1473bc3
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions src/class.coord.js → src/class.coord.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,43 @@
//@ts-check

import { round } from "./utils";

type Axle = "x"|"y";

/**
* Class representing a 2d xy coordinate
*/
export class Coord {
constructor(x, y) {
this.set(x, y);
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}

set(x, y) {
set(x: number, y: number) {
this.x = x;
this.y = y;
}

static fromObject(obj) {
return new Coord(obj.x, obj.y);
static fromObject(obj: Object) {
return new Coord((<Coord>obj).x, (<Coord>obj).y);
}

/**
* returns the distance between two xy coordinates
* @param {Coord} coord1
* @param {Coord} coord2
*/
static dist(coord1, coord2) {
static dist(coord1: Coord, coord2: Coord) {
return Math.sqrt(Math.pow(coord1.x - coord2.x, 2) + Math.pow(coord1.y - coord2.y, 2));
}

/**
*exchange a value between two xy coordinates
* @param {Coord} coord1
* @param {Coord} coord2
* @param {string} val
* @param {Axle} val
*/
static swap(coord1, coord2, val) {
static swap(coord1: Coord, coord2: Coord, val: Axle) {
let tmp = coord1[val];
coord1[val] = coord2[val];
coord2[val] = tmp;
Expand All @@ -52,15 +55,15 @@ export class Coord {
* returns the sum of two xy coordinates
* @param {Coord} coord
*/
sum(coord) {
sum(coord: Coord) {
return new Coord(this.x + coord.x, this.y + coord.y);
}

/**
* Add the value of the given coordinate to the current one
* @param {Coord} coord
*/
add(coord) {
add(coord: Coord) {
this.x += coord.x;
this.y += coord.y;
}
Expand All @@ -69,15 +72,15 @@ export class Coord {
* returns the difference of two xy coordinates
* @param {Coord} coord
*/
diff(coord) {
diff(coord: Coord) {
return new Coord(this.x - coord.x, this.y - coord.y);
}

/**
* Substract the value of the given coordinate to the current one
* @param {Coord} coord
*/
sub(coord) {
sub(coord: Coord) {
this.x -= coord.x;
this.y -= coord.y;
}
Expand All @@ -87,15 +90,15 @@ export class Coord {
* Alias of add
* @param {Coord} coord
*/
move(coord) {
move(coord: Coord) {
this.add(coord);
}

getPosition() {
return this;
}

setPosition(coord) {
setPosition(coord: Coord) {
this.set(coord.x, coord.y);
}
//------------------------- End Interface Movable --------------------------------
Expand All @@ -108,11 +111,11 @@ export class Coord {
return new Coord(- this.x, -this.y);
}

toStr(dec, val, scale) {
toStr(dec: number, val: Axle, scale: number) {
return round(this[val] * scale, dec)
}

toHtml(dec, scale = 1) {
toHtml(dec: number, scale = 1) {
return this.toStr(dec, "x", scale) + "," + this.toStr(dec, "y", scale);
}

Expand Down

0 comments on commit 1473bc3

Please sign in to comment.