From 5b2e6b1ad5977ea41eb5d59b33f6f897530b12fd Mon Sep 17 00:00:00 2001 From: Timothy Brookes Date: Wed, 15 Jun 2022 09:51:27 +0100 Subject: [PATCH] fix: rounding inconsistency for negative values in math.allocate --- src/utils/__tests__/math.test.ts | 3 +++ src/utils/math.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/utils/__tests__/math.test.ts b/src/utils/__tests__/math.test.ts index 6631a59..16809dd 100644 --- a/src/utils/__tests__/math.test.ts +++ b/src/utils/__tests__/math.test.ts @@ -117,4 +117,7 @@ describe('allocate()', () => { it('returns an array that distributes the provided number to each weight, using the negative weights to increase the amount that can be allocated', () => { expect(allocate(100, [-5, 15], 10)).toEqual([-50, 150]); }); + it('returns the same distributions with negative and positive values', () => { + expect(allocate(21, [1, 5, 4], 10).map((value) => Math.abs(value))).toEqual(allocate(-21, [1, 5, 4], 10).map((value) => Math.abs(value))) + }); }); diff --git a/src/utils/math.ts b/src/utils/math.ts index cc2713d..e508411 100644 --- a/src/utils/math.ts +++ b/src/utils/math.ts @@ -89,7 +89,7 @@ export function allocate( let i = 0; while (i < length - 1) { const share = (weights[i] / total) * n + crumbs; - const wholeShare = Math.floor(share); + const wholeShare = Math.trunc(share); crumbs = share - wholeShare; sum += wholeShare; shares[i] = wholeShare;