90 lines
1.9 KiB
JavaScript
90 lines
1.9 KiB
JavaScript
|
|
/*
|
|
* Énoncé:
|
|
* Étant donné les classes Shape & Point définies ci dessous, implémenter les sous classes de Shape
|
|
* Circle et Square et leur méthode getPerimeter respective.
|
|
*/
|
|
|
|
/* Shape */
|
|
|
|
function Shape() {}
|
|
|
|
Shape.prototype.getPerimeter = function() {
|
|
throw new Error('La méthode getPerimeter doit être implémentée par les sous classes !');
|
|
};
|
|
|
|
/* Point */
|
|
|
|
function Point(x, y) {
|
|
this.x = x;
|
|
this.y = y;
|
|
}
|
|
|
|
Point.prototype.getDistanceFrom = function(point) {
|
|
if( !(point instanceof Point) ) {
|
|
throw new Error('L\'argument "point" doit être une instance de Point !');
|
|
}
|
|
return Math.sqrt( (this.x-point.x)*(this.x-point.x) + (this.y-point.y)*(this.y-point.y));
|
|
};
|
|
|
|
/* Square */
|
|
|
|
function Square(p1, p2, p3, p4) {
|
|
this.p1 = p1;
|
|
this.p2 = p2;
|
|
this.p3 = p3;
|
|
this.p4 = p4;
|
|
}
|
|
|
|
Square.prototype = Object.create(Shape.prototype);
|
|
|
|
Square.prototype.getPerimeter = function() {
|
|
return this.p1.getDistanceFrom(this.p2) +
|
|
this.p2.getDistanceFrom(this.p3) +
|
|
this.p3.getDistanceFrom(this.p4) +
|
|
this.p4.getDistanceFrom(this.p1)
|
|
;
|
|
};
|
|
|
|
/* Circle */
|
|
|
|
function Circle(center, radius) {
|
|
this.center = center;
|
|
this.radius = radius;
|
|
}
|
|
|
|
Circle.prototype = Object.create(Shape.prototype);
|
|
|
|
Circle.prototype.getPerimeter = function() {
|
|
return Math.PI * 2 * this.radius;
|
|
};
|
|
|
|
/* Tests */
|
|
|
|
var p1 = new Point(1, 5);
|
|
var p2 = new Point(2, 6);
|
|
var p3 = new Point(2, -10);
|
|
var p4 = new Point(7, -2);
|
|
|
|
var s = new Square(p1, p2, p3, p4);
|
|
|
|
try {
|
|
|
|
console.log( s instanceof Square ); // -> true
|
|
console.log( s instanceof Shape ); // -> true
|
|
console.log( s.getPerimeter() ); // -> 36.06773915172259
|
|
|
|
} catch(err) {
|
|
console.error(err);
|
|
}
|
|
|
|
var c = new Circle(p1, 5);
|
|
|
|
try {
|
|
console.log( c instanceof Circle ); // -> true
|
|
console.log( c instanceof Shape ); // -> true
|
|
console.log( c.getPerimeter() ); // -> 31.41592653589793
|
|
} catch(err) {
|
|
console.error(err);
|
|
}
|