From 6606a6f04d159ccd068b05db0e0ef6bf48523517 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Tue, 9 May 2023 00:24:33 +0200 Subject: [PATCH] refactor: align statistic helpers return for empty data set MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/utils/Utils.ts | 7 +++++-- test/utils/UtilsTest.ts | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 717a6e68..4f89179f 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -337,6 +337,9 @@ export class Utils { } public static median(dataSet: number[]): number { + if (Utils.isEmptyArray(dataSet)) { + return 0; + } if (Array.isArray(dataSet) === true && dataSet.length === 1) { return dataSet[0]; } @@ -345,12 +348,12 @@ export class Utils { } // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree - public static percentile(dataSet: number[], percentile: number): number | undefined { + public static percentile(dataSet: number[], percentile: number): number { if (percentile < 0 && percentile > 100) { throw new RangeError('Percentile is not between 0 and 100'); } if (Utils.isEmptyArray(dataSet)) { - return undefined; + return 0; } const sortedDataSet = dataSet.slice().sort((a, b) => a - b); if (percentile === 0 || sortedDataSet.length === 1) { diff --git a/test/utils/UtilsTest.ts b/test/utils/UtilsTest.ts index 35294d07..885f7085 100644 --- a/test/utils/UtilsTest.ts +++ b/test/utils/UtilsTest.ts @@ -331,6 +331,7 @@ describe('Utils test suite', () => { }); it('Verify median()', () => { + expect(Utils.median([])).toBe(0); const array0 = [0.08]; expect(Utils.median(array0)).toBe(0.08); const array1 = [0.25, 4.75, 3.05, 6.04, 1.01, 2.02, 5.03]; @@ -338,7 +339,7 @@ describe('Utils test suite', () => { }); it('Verify percentile()', () => { - expect(Utils.percentile([], 25)).toBe(undefined); + expect(Utils.percentile([], 25)).toBe(0); const array0 = [0.08]; expect(Utils.percentile(array0, 50)).toBe(0.08); const array1 = [0.25, 4.75, 3.05, 6.04, 1.01, 2.02, 5.03]; -- 2.34.1