formations/javascript/base/exercices/heritage/heritage-src.js

87 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 Polygon(p1, p2, p3, p4) {
this._points = Array.prototype.slice.call(arguments); // Arguments to array
}
Polygon.prototype = Object.create(Shape.prototype);
Polygon.prototype.getPerimeter = function() {
var points = this._points;
return points.reduce(function(perimeter, point, i) {
return perimeter + point.getDistanceFrom(points[(i+1)%points.length]);
}, 0);
};
/* 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);
try {
var poly = new Polygon(p1, p2, p3, p4);
console.log( poly instanceof Polygon ); // -> true
console.log( poly instanceof Shape ); // -> true
console.log( poly.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);
}