diff --git a/src/figuresClasses.ts b/src/figuresClasses.ts index 753711299..7956f26d4 100644 --- a/src/figuresClasses.ts +++ b/src/figuresClasses.ts @@ -1,11 +1,81 @@ -export interface Figure {} +export type FigureColor = 'red' | 'green' | 'blue'; -export class Triangle implements Figure {} +export interface Figure { + shape: 'triangle' | 'circle' | 'rectangle'; + color: FigureColor; + getArea(): number; +} + +function validatePositiveLength(value: number, name: string): void { + if (value <= 0) { + throw new Error(`${name} must be greater than 0`); + } +} + +export class Triangle implements Figure { + shape: 'triangle' = 'triangle'; + + constructor( + public color: FigureColor, + public a: number, + public b: number, + public c: number, + ) { + validatePositiveLength(a, 'a'); + validatePositiveLength(b, 'b'); + validatePositiveLength(c, 'c'); -export class Circle implements Figure {} + const sortedSides = [a, b, c].sort((x, y) => y - x); + const longestSide = sortedSides[0]; + const sumOfOtherSides = sortedSides[1] + sortedSides[2]; + + if (longestSide >= sumOfOtherSides) { + throw new Error(`Sides ${a}, ${b} and ${c} can't form a triangle`); + } + } + + getArea(): number { + const s = (this.a + this.b + this.c) / 2; + const area = Math.sqrt(s * (s - this.a) * (s - this.b) * (s - this.c)); + + return Math.floor(area * 100) / 100; + } +} -export class Rectangle implements Figure {} +export class Circle implements Figure { + shape: 'circle' = 'circle'; + + constructor( + public color: FigureColor, + public radius: number, + ) { + validatePositiveLength(radius, 'radius'); + } + + getArea(): number { + const area = Math.PI * this.radius * this.radius; + + return Math.floor(area * 100) / 100; + } +} + +export class Rectangle implements Figure { + shape: 'rectangle' = 'rectangle'; + + constructor( + public color: FigureColor, + public width: number, + public height: number, + ) { + validatePositiveLength(width, 'width'); + validatePositiveLength(height, 'height'); + } + + getArea(): number { + return Math.floor(this.width * this.height * 100) / 100; + } +} -export function getInfo(figure): string { - return typeof figure; +export function getInfo(figure: Figure): string { + return `A ${figure.color} ${figure.shape} - ${figure.getArea()}`; }