Skip to content

Commit f0e8249

Browse files
committed
Move area method to Geometry (HowProgrammingWorks#1)
1 parent 185d4aa commit f0e8249

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

Diff for: JavaScript/8-geometry.js

+14-13
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,6 @@ class Polygon {
1616
this.points = points;
1717
}
1818

19-
get area() {
20-
let value = 0;
21-
let d = this.points[this.points.length - 1];
22-
for (const p of this.points) {
23-
value += p.x * d.y - d.x * p.y;
24-
d = p;
25-
}
26-
return Math.abs(value) / 2;
27-
}
28-
2919
toString() {
3020
return this.points.map((p) => p.toString()).join('; ');
3121
}
@@ -62,23 +52,34 @@ class Geometry {
6252
point.y = x * sin + y * cos;
6353
}
6454
}
55+
56+
static area(polygon) {
57+
const { points } = polygon
58+
let value = 0;
59+
let d = points[points.length - 1];
60+
for (const p of points) {
61+
value += p.x * d.y - d.x * p.y;
62+
d = p;
63+
}
64+
return Math.abs(value) / 2;
65+
}
6566
}
6667

6768
// Usage
6869

6970
const rect = new Rect(10, 10, 30, -10);
7071
console.log(rect);
71-
console.log(rect.area);
72+
console.log(Geometry.area(rect));
7273

7374
console.log('Rotate 45');
7475
Geometry.rotate(rect, 45);
7576
console.log(rect);
76-
console.log(rect.area);
77+
console.log(Geometry.area(rect));
7778

7879
const triangle = new Triangle(0, 0, 15, 0, 0, 15);
7980
console.log(triangle);
8081
console.log('Rotate 90');
8182
Geometry.rotate(triangle, 90);
8283
console.log(triangle);
83-
console.log(triangle.area);
84+
console.log(Geometry.area(triangle));
8485
console.log(`${triangle}`);

0 commit comments

Comments
 (0)