1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-12-08 00:45:29 +01:00

feat(solutions): add triangle-type/typescript/function

This commit is contained in:
Divlo 2021-06-30 12:28:30 +02:00
parent b045c70c1a
commit 1dbe602f15
No known key found for this signature in database
GPG Key ID: 185ED2F15F104E52
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# triangle-type/typescript/function
Created by [@Divlo](https://github.com/Divlo) on 30 June 2021.

View File

@ -0,0 +1,54 @@
import readline from 'readline'
const removeByIndex = <T = any>(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)
}