Skip to content

Commit

Permalink
perf(g.Rect): prevent unnecessary object instantiation in containsPoi…
Browse files Browse the repository at this point in the history
…nt()

Rect.containsPoint is called many times with a Point instance as argument.
Avoiding the new Point call improves loading times significantly on larger papers.
  • Loading branch information
coyoteecd authored Aug 31, 2023
1 parent 55de376 commit b8b8d9d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/g/rect.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,10 @@ Rect.prototype = {

// @return {bool} true if point p is inside me.
containsPoint: function(p) {
p = new Point(p);

if (!(p instanceof Point)) {
p = new Point(p);
}
return p.x >= this.x && p.x <= this.x + this.width && p.y >= this.y && p.y <= this.y + this.height;
},

Expand Down
20 changes: 20 additions & 0 deletions test/geometry/rect.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,27 @@ QUnit.module('rect', function() {
});

QUnit.module('containsPoint(point)', function() {

QUnit.test('returns TRUE when a point is inside the rect', function(assert) {
assert.ok((new g.Rect(50, 50, 50, 50).containsPoint(new g.Point(75, 75))), 'inside for Point');
assert.ok((new g.Rect(50, 50, 50, 50).containsPoint({ x: 75, y: 75 })), 'inside for object');
assert.ok((new g.Rect(50, 50, 50, 50).containsPoint('75@75')), 'inside for string coords separated by @');
assert.ok((new g.Rect(50, 50, 50, 50).containsPoint('75 75')), 'inside for string coords separated by space');
});

QUnit.test('returns TRUE when a point is a corner of the rect', function(assert) {
assert.ok(new g.Rect(50, 50, 50, 50).containsPoint(new g.Point(50, 50)));
assert.ok(new g.Rect(50, 50, 50, 50).containsPoint(new g.Point(50, 100)));
assert.ok(new g.Rect(50, 50, 50, 50).containsPoint(new g.Point(100, 50)));
assert.ok(new g.Rect(50, 50, 50, 50).containsPoint(new g.Point(100, 100)));
});

QUnit.test('returns TRUE when a point is outside the rect', function(assert) {
assert.notOk((new g.Rect(50, 50, 50, 50).containsPoint(new g.Point(49, 75))), 'outside for Point');
assert.notOk((new g.Rect(50, 50, 50, 50).containsPoint({ x: 101, y: 75 })), 'outside for object');
assert.notOk((new g.Rect(50, 50, 50, 50).containsPoint('75@101')), 'outside for string coords separated by @');
assert.notOk((new g.Rect(50, 50, 50, 50).containsPoint('75 49')), 'outside for string coords separated by space');
});
});

QUnit.module('containsRect(rect)', function() {
Expand Down

0 comments on commit b8b8d9d

Please sign in to comment.