One of the most fitting topics to practice modeling skills is geometry. Unlike other areas of mathematics, it's visually conceivable and directly accessible for everyone. First, let's recall the basic concepts that we'll be dealing with.
A Coordinate (Cartesian) Plane is the plane on which a coordinate system is defined. The coordinates are given on two right-angle intersecting lines (numerical axes) x
and y
.
6 | y
5 |
4 |
3 | . (2, 3)
2 |
1 |
|
----------------------------------------------------
| 1 2 3 4 5 6 x
|
|
|
|
|
|
The simplest primitive that can be placed on the plane is a point. Its position is defined by two coordinates, and in mathematics it's written as (2, 3)
, where the first number is the x-axis
, coordinate, and the second is the y-axis
coordinate. In code, it can be represented as an array of two elements.
const point = [2, 3];
This is already enough to perform some useful geometric actions. For example, to find a symmetric point relative to the x-axis
, it's sufficient to invert the second number (i.e., turn a + to a - and vice versa).
6 | y
5 |
4 |
3 | . (2, 3)
2 |
1 |
|
----------------------------------------------------
| 1 2 3 4 5 6 x
-1 |
-2 |
-3 | . (2, -3)
-4 |
-5 |
-6 |
const point = [2, 3];
const [x, y] = point;
// x = 2, y = 3
const symmetricalPoint = [x, -y];
// x = 2, y = -3
Occasionally, you need to find a point that's directly in between two points (they may also say that you need to find the middle of a segment). This point is calculated by finding the arithmetic mean of each of the coordinates. I.e., the x
coordinate of the midpoint is (x1 + x2) / 2
, and the y coordinate is y
— (y1 + y2) / 2
.
const getMiddlePoint = (p1, p2) => {
const x = (p1[0] + p2[0]) / 2;
const y = (p1[1] + p2[1]) / 2;
return [x, y];
};
const point1 = [2, 3];
const point2 = [-4, 0];
console.log(getMiddlePoint(point1, point2)); // => [-1, 1.5]
There are many such operations in geometry. It makes sense to put all functions related to working with points in the points
module from the code architecture viewpoint.
In turn, the points are combined into segments. Each segment is defined by a pair of points — the beginning and the end. We can define a segment with code just like a point - an array of two elements where each element is a point.
const point1 = [3, 4];
const point2 = [-8, 10];
const segment = [point1, point2];
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.