Skip to content

Commit

Permalink
fix: prevent division by zero in bezier (#785)
Browse files Browse the repository at this point in the history
  • Loading branch information
samvimes01 authored Aug 23, 2024
1 parent 6d27df6 commit 1ca425e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/bezier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class Bezier {
const dxm = m1.x - m2.x;
const dym = m1.y - m2.y;

const k = l2 / (l1 + l2);
const k = l1 + l2 == 0 ? 0 : l2 / (l1 + l2);
const cm = { x: m2.x + dxm * k, y: m2.y + dym * k };

const tx = s2.x - cm.x;
Expand Down
19 changes: 19 additions & 0 deletions tests/bezier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,25 @@ describe('.fromPoints', () => {
expect(curve.endWidth).toBe(2);
});
});

it('returns a new Bézier when points are equal and division by zero may occur', () => {
const now = Date.now();

freezeTimeAt(now, () => {
const p1 = new Point(54.4, 10.9, 0.5);
const p2 = new Point(54.4, 10.9, 0.5);
const p3 = new Point(54.4, 10.9, 0.5);
const p4 = new Point(54.4, 10.9, 0.5);
const curve = Bezier.fromPoints([p1, p2, p3, p4], { start: 1, end: 1 });

expect(curve.startPoint).toEqual(p2);
expect(curve.control1).toEqual(new Point(54.4, 10.9));
expect(curve.control2).toEqual(new Point(54.4, 10.9));
expect(curve.endPoint).toBe(p3);
expect(curve.startWidth).toBe(1);
expect(curve.endWidth).toBe(1);
});
});
});

describe('#length', () => {
Expand Down

0 comments on commit 1ca425e

Please sign in to comment.