From 1dbe602f154896df7b81017ef1f3465965b92fe9 Mon Sep 17 00:00:00 2001 From: Divlo Date: Wed, 30 Jun 2021 12:28:30 +0200 Subject: [PATCH] feat(solutions): add `triangle-type/typescript/function` --- .../solutions/typescript/function/README.md | 3 ++ .../solutions/typescript/function/solution.ts | 54 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 challenges/triangle-type/solutions/typescript/function/README.md create mode 100644 challenges/triangle-type/solutions/typescript/function/solution.ts diff --git a/challenges/triangle-type/solutions/typescript/function/README.md b/challenges/triangle-type/solutions/typescript/function/README.md new file mode 100644 index 0000000..05085c5 --- /dev/null +++ b/challenges/triangle-type/solutions/typescript/function/README.md @@ -0,0 +1,3 @@ +# triangle-type/typescript/function + +Created by [@Divlo](https://github.com/Divlo) on 30 June 2021. diff --git a/challenges/triangle-type/solutions/typescript/function/solution.ts b/challenges/triangle-type/solutions/typescript/function/solution.ts new file mode 100644 index 0000000..78d1d46 --- /dev/null +++ b/challenges/triangle-type/solutions/typescript/function/solution.ts @@ -0,0 +1,54 @@ +import readline from 'readline' + +const removeByIndex = (array: T[], index: number): T[] => { + const result = [...array] + result.splice(index, 1) + return result +} + +type TriangleType = 'impossible' | 'equilateral' | 'isosceles' | 'scalene' + +class Triangle { + public sides: number[] + public type: TriangleType + + constructor(sides: number[]) { + this.sides = sides + this.type = this.getType() + } + + private getType(): TriangleType { + const largestSide = Math.max(...this.sides) + const largestSideIndex = this.sides.findIndex((side) => side === largestSide) + const otherSides = removeByIndex(this.sides, largestSideIndex) + const isImpossible = otherSides[0] + otherSides[1] < largestSide + if (isImpossible) { + return 'impossible' + } + const uniqueSides = [...new Set(this.sides)] + const isEquilateral = uniqueSides.length === 1 + const isIsocseles = uniqueSides.length === 2 + if (isEquilateral) { + return 'equilateral' + } + if (isIsocseles) { + return 'isosceles' + } + return 'scalene' + } +} + +const triangleSides: number[] = [] +const readlineInterface = readline.createInterface({ + input: process.stdin, + output: process.stdout +}) +readlineInterface.on('line', (value) => { + triangleSides.push(Number(value)) +}) +readlineInterface.on('close', solution) + +function solution(): void { + const triangle = new Triangle(triangleSides) + console.log(triangle.type) +}