Pages

Thursday, October 27, 2016

Quadrilateral Tests

function QuadrilateralTests(epsilon) {

  var methods = [];
  methods.push({name: "area", args: [""]});
  methods.push({name: "circumference", args: [""]});
  methods.push({name: "side", args: [0,1,2,3]});
  methods.push({name: "angle", args: [0,1,2,3]});

  var difference;

  function closeEnough(a, b) {
    difference = Math.abs(a-b);
    return difference < epsilon;
  }

  function test(f) {
    var q = f();
    for (var i=0; i < methods.length; i++) {
      var name = methods[i].name;
      var args = methods[i].args;
      for (var j=0; j < args.length; j++) {
        var arg = args[j];
        if (!closeEnough(q[name](arg), f[name+arg])) {
          var errorMessage = "TEST FAILED: " + f.name + "." + name;
          console.log(errorMessage);
          console.log("Expected: " + f[name+arg]);
          console.log("Actual: " + q[name](arg));
          console.log("Difference: " + difference);
          console.log("Epsilon: " + epsilon);
          throw new Error(errorMessage);
        }
      }
    }
  }

  function isoscelesTrapezoid() {
    return new Quadrilateral(1, Math.sqrt(2), 3, 135, 45);
  }
  isoscelesTrapezoid.area = 2;
  isoscelesTrapezoid.circumference = 6.82842712474619;
  isoscelesTrapezoid.side0 = 1;
  isoscelesTrapezoid.side1 = Math.sqrt(2);
  isoscelesTrapezoid.side2 = 3;
  isoscelesTrapezoid.side3 = Math.sqrt(2);
  isoscelesTrapezoid.angle0 = 135;
  isoscelesTrapezoid.angle1 = 135;
  isoscelesTrapezoid.angle2 = 45;
  isoscelesTrapezoid.angle3 = 45;

  function unitSquare() {
    return new Quadrilateral(1, 1, 1, 90, 90);
  }
  unitSquare.area = 1;
  unitSquare.circumference = 4;
  unitSquare.side0 = 1;
  unitSquare.side1 = 1;
  unitSquare.side2 = 1;
  unitSquare.side3 = 1;
  unitSquare.angle0 = 90;
  unitSquare.angle1 = 90;
  unitSquare.angle2 = 90;
  unitSquare.angle3 = 90;

  test(unitSquare);
  test(isoscelesTrapezoid);
}

QuadrilateralTests(1e-13);