Skip to content

Instantly share code, notes, and snippets.

@rarecoil
Last active January 30, 2020 06:45
Show Gist options
  • Save rarecoil/f8aba5348431c6442868fcac172a7e95 to your computer and use it in GitHub Desktop.
Save rarecoil/f8aba5348431c6442868fcac172a7e95 to your computer and use it in GitHub Desktop.
A ridiculous, over-the-top classifier answer for a friend's (Java) computer science class, that robustly solves the problem in TypeScript and ignores the constraints of the professor.
export default class TriangleClassifier {
/**
* Return a string classifying a triangle based upon its sides.
*
* @param a Side A.
* @param b Side B.
* @param c Side C.
*/
public static classify(a:number, b:number, c:number):"isosceles"|"scalene"|"equilateral" {
// validate for weird edge cases
TriangleClassifier.throwIfNaN(a, b, c);
TriangleClassifier.throwIfNegativeOrZero(a, b, c);
TriangleClassifier.throwIfInvalid(a, b, c);
if (a === b && b === c) {
return 'equilateral';
}
if ((a === b) || (a === c) || (b === c)) {
return 'isosceles';
}
return 'scalene';
}
/**
* Throw an error if any side is NaN, which is typeof 'number'.
*/
protected static throwIfNaN(a:number, b:number, c:number):void {
[a, b, c].map((x:number) => {
if (isNaN(x)) {
throw new TriangleClassifierValidationError("Input is NaN");
}
})
}
/**
* Throw an error if any side is negative, because that's ridiculous.
*/
protected static throwIfNegativeOrZero(a:number, b:number, c:number):void {
[a, b, c].map((x:number) => {
if (x <= 0) {
throw new TriangleClassifierValidationError("Input is negative");
}
});
}
/**
* Throw an error if the triangle is not a valid triangle.
*/
protected static throwIfInvalid(a:number, b:number, c:number):void {
if ( ((a + b) > c) || ((a + c ) > b) || ((b + c) > a) ) {
return;
}
throw new TriangleClassifierValidationError("Sides do not form a triangle");
}
}
export class TriangleClassifierValidationError extends Error {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment