Correction exo heritge js

This commit is contained in:
wpetit 2015-04-02 08:43:33 +02:00
parent b00c6dd3f4
commit c645af4112
3 changed files with 27 additions and 26 deletions

View File

@ -29,21 +29,17 @@ Point.prototype.getDistanceFrom = function(point) {
/* Square */
function Square(p1, p2, p3, p4) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
function Polygon(p1, p2, p3, p4) {
this._points = Array.prototype.slice.call(arguments); // Arguments to array
}
Square.prototype = Object.create(Shape.prototype);
Polygon.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)
;
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 */
@ -66,13 +62,14 @@ 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
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);

View File

@ -2,7 +2,7 @@
/*
* É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.
* Circle et Polygon et leur méthode getPerimeter respective.
*/
/* Shape */
@ -29,9 +29,9 @@ Point.prototype.getDistanceFrom = function(point) {
// ---------------------- À compléter -------------------------------
/* Square */
/* Polygon */
function Square(p1, p2, p3, p4) {
function Polygon(p1, p2, p3, p4) {
}
@ -50,24 +50,28 @@ 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
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 {
var c = new Circle(p1, 5);
console.log( c instanceof Circle ); // -> true
console.log( c instanceof Shape ); // -> true
console.log( c.getPerimeter() ); // -> 31.41592653589793
} catch(err) {
console.error(err);
}

View File

@ -1,5 +1,5 @@
<html>
<body>
<script src="heritage.js"></script>
<script src="heritage-src.js"></script>
</body>
</html>