triangle.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var Triangle = function(a, b, c){

  var satisfiesTriangleInequality = function() {
    var largest = Math.max(a, b, c);
    if (a == largest) return b + c > a;
    if (b == largest) return a + c > b;
    if (c == largest) return a + b > c;
  };

  var validateTriangle = function() {
    if ([a, b, c].some(function(x) { return x === 0; }))
      throw "Triangle cannot have zero size";

    if ([a, b, c].some(function(x) { return x < 0; }))
      throw "Sides cannot be negative";

    if (!satisfiesTriangleInequality())
      throw "Not a valid triangle";
  };

  this.kind = function() {
    validateTriangle();

    if (a == b && b == c) return 'equilateral';
    if (a == b || b == c || a == c) return 'isosceles';
    return 'scalene';
  };
};

module.exports = Triangle;

Comments


You're not logged in right now. Please login via GitHub to comment