From c1ccc10a32fcbd18b9fdda32ec656791818f5856 Mon Sep 17 00:00:00 2001 From: Oleksandr Korneiko Date: Fri, 23 Aug 2024 16:25:54 +0300 Subject: [PATCH] fix: prevent division by zero in bezier --- src/bezier.ts | 2 +- tests/bezier.test.ts | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/bezier.ts b/src/bezier.ts index 17ba5954..9fddfd2d 100644 --- a/src/bezier.ts +++ b/src/bezier.ts @@ -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; diff --git a/tests/bezier.test.ts b/tests/bezier.test.ts index b95e1f26..b962b8f7 100644 --- a/tests/bezier.test.ts +++ b/tests/bezier.test.ts @@ -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', () => {