kstoyanov

04. Class Hierarchy

Oct 15th, 2020 (edited)
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function classHierarchy() {
  2.   class Figure {
  3.     constructor(unit = 'cm') {
  4.       this.unit = unit;
  5.     }
  6.  
  7.     get area() {
  8.       return NaN;
  9.     }
  10.  
  11.     changeUnits(x) {
  12.       this.unit = x;
  13.     }
  14.  
  15.     calcWidthUnit(x) {
  16.       const units = {
  17.         m: 0.01,
  18.         cm: 1,
  19.         mm: 10,
  20.       };
  21.  
  22.       return x * units[this.unit];
  23.     }
  24.  
  25.     toString() {
  26.       return `Figures units: ${this.unit} Area: ${this.area}`;
  27.     }
  28.   }
  29.  
  30.   class Circle extends Figure {
  31.     constructor(radius = 0, ...rest) {
  32.       super(...rest);
  33.       this.radius = radius;
  34.     }
  35.  
  36.     get area() {
  37.       return Math.PI * Math.pow(super.calcWidthUnit(this.radius), 2);
  38.     }
  39.  
  40.     toString() {
  41.       return `${super.toString()} - radius: ${super.calcWidthUnit(this.radius)}`;
  42.     }
  43.   }
  44.  
  45.   class Rectangle extends Figure {
  46.     constructor(width = 0, height = 0, ...rest) {
  47.       super(...rest);
  48.       this._width = width;
  49.       this._height = height;
  50.     }
  51.  
  52.     get height() {
  53.       return this.calcWidthUnit(this._height);
  54.     }
  55.  
  56.     get width() {
  57.       return this.calcWidthUnit(this._width);
  58.     }
  59.  
  60.     set height(newHeight) {
  61.       this._height = newHeight;
  62.     }
  63.  
  64.     set width(newWidth) {
  65.       this._width = newWidth;
  66.     }
  67.  
  68.     get area() {  
  69.       return this.calcWidthUnit(this._width) * this.calcWidthUnit(this._height);
  70.     }
  71.  
  72.     toString() {
  73.       return `${super.toString()} - width: ${this.calcWidthUnit(this._width)}, height: ${this.calcWidthUnit(this._height)}`;
  74.     }
  75.   }
  76.  
  77.   return { Figure, Circle, Rectangle };
  78. }
Advertisement
Add Comment
Please, Sign In to add comment