Shapes with Object.create
Some JavaScript shape objects implemented with Object.create, with unit tests, of course
by Ray Toal
HTML
<script src="https://code.jquery.com/qunit/qunit-git.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-git.css">
<div id="qunit"></div>
<div id="qunit-fixture"></div>
JavaScript
/*
* A circle datatype.
*
* Synopsis:
* let c = Circle.create(10);
* c.radius ==> 10
* c.area() ==> 314.1592653589793
* c.perimiter() ==> 62.83185307179586
*/
let Circle = {
create(r) {
let c = Object.create(this);
c.radius = r;
return c;
},
area() {
return Math.PI * this.radius * this.radius;
},
perimeter() {
return 2 * Math.PI * this.radius;
}
};
/*
* A rectangle datatype.
*
* Synopsis:
* let r = Rectangle.create(5, 8);
* r.length ==> 5
* r.width ==> 8
* r.area() ==> 40
* r.perimeter() ==> 26
*/
let Rectangle = {
create(w, h) {
r = Object.create(this);
r.width = w;
r.height = h;
return r;
},
area() {
return this.width * this.height;
},
perimeter() {
return 2 * (this.width + this.height);
}
};
// TESTS
QUnit.test("Circle tests", t => {
let c = Circle.create(10);
t.equal(c.radius, 10);
t.equal(c.area(), 100 * Math.PI);
t.equal(c.perimeter(), 20 * Math.PI);
});
QUnit.test("Rectangle tests", t => {
let r = Rectangle.create(5, 8);
t.equal(r.width, 5);
t.equal(r.height, 8);
t.equal(r.area(), 40);
t.equal(r.perimeter(), 26);
});