Write a small class, and use it to describe rectangles.
What to build
A class Rectangle with a constructor and three methods.
Requirements
new Rectangle(width, height)stores the two sizes.area()returns the area.perimeter()returns the distance around the edge.isSquare()returns true when the two sides are equal.- For each input line, print
area A perimeter P square, orarea A perimeter P not square.
Input
Several lines, each two whole numbers separated by a space.
Output
One line per input line.
Constraints
There are from 1 to 50 lines, and the numbers are from 1 to 1000.
Example
Input:
3 4
Output:
area 12 perimeter 14 not square
Why it works
Each object carries its own sizes, so the methods need no parameters. this tells a method which rectangle it is working on.
Examples
Example 1 · Input
3 4
Expected output
area 12 perimeter 14 not square
Example 2 · Input
5 5
Expected output
area 25 perimeter 20 square
Hints
Hint 1
The constructor stores this.width and this.height.
Hint 2
A method such as area() uses this.width, not a bare width.
Hint 3
Print with a template string, calling the methods inside it.
Solution
Show one correct solution (try it yourself first)
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
perimeter() {
return 2 * (this.width + this.height);
}
isSquare() {
return this.width === this.height;
}
}
let line = prompt();
while (line !== null) {
const [w, h] = line.split(" ").map(Number);
const r = new Rectangle(w, h);
console.log(`area ${r.area()} perimeter ${r.perimeter()} ${r.isSquare() ? "square" : "not square"}`);
line = prompt();
}