Write a Shape base class with Circle and Rectangle subclasses that each compute their own area.
new Shape(name) makes a shape with that name. Its area() must be overridden: calling it on a shape that doesn't override it throws an Error.
describe() returns "<name> with area <area>", with the area always written to 2 decimal places, so an area of 6 is 6.00.
Circle(radius) and Rectangle(width, height) extend Shape and compute their own area. A circle's name is "circle", and a rectangle's is "rectangle".
Add a static Shape.compare(a, b) that returns a.area() - b.area(), so shapes can be sorted by area.
class Shape {
// your code
}
class Circle extends Shape {
// your code
}
class Rectangle extends Shape {
// your code
}
// new Circle(1).describe(); // "circle with area 3.14"
// new Rectangle(2, 3).area(); // 6
// new Rectangle(2, 3).describe(); // "rectangle with area 6.00"
// new Shape("blob").area(); // throws an Error
// [new Circle(2), new Rectangle(1, 1)].sort(Shape.compare).map((shape) => shape.name);
// // ["rectangle", "circle"]: the smaller area comes first
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…