Skip to content
Exercise · Classes and prototypes · lesson 12 of 12

Exercise: shapes

The starter code has the finished class Shape and the beginnings of its two subclasses: Rect with the width width and the height height, and Circle with the radius radius. In Rect and Circle, complete the constructors and the area() methods, which return the area; for a circle it is Math.PI * radius * radius. Write a function function totalArea(shapes) that returns the sum of the areas of all shapes in the array. The tests create shapes with new, for example new Rect(2, 3).

  • new Rect(2, 3).area() → 6
  • new Circle(1).area() → 3.141592653589793
  • totalArea([new Rect(1, 1), new Rect(2, 5)]) → 11

Constraints: sizes are positive numbers; a fractional result is compared to within 0.000000001; the array may mix rectangles and circles, and for an empty array totalArea returns 0.

Do not add extra imports unless the task says so explicitly.

shapes.js — javascript
javascript · 26 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way