From 90d6701c50f71a2c41e2052b3196c52b4ae500df Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sun, 3 Sep 2023 15:48:20 +0200 Subject: [PATCH] perf: generalize optimized min/max MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/pools/abstract-pool.ts | 10 ++++++---- src/utils.ts | 7 +++++-- tests/utils.test.js | 14 ++++++++++++++ 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/pools/abstract-pool.ts b/src/pools/abstract-pool.ts index ab7fcf51..6668361f 100644 --- a/src/pools/abstract-pool.ts +++ b/src/pools/abstract-pool.ts @@ -14,7 +14,9 @@ import { average, isKillBehavior, isPlainObject, + max, median, + min, round, updateMeasurementStatistics } from '../utils' @@ -414,14 +416,14 @@ export abstract class AbstractPool< .runTime.aggregate && { runTime: { minimum: round( - Math.min( + min( ...this.workerNodes.map( (workerNode) => workerNode.usage.runTime?.minimum ?? Infinity ) ) ), maximum: round( - Math.max( + max( ...this.workerNodes.map( (workerNode) => workerNode.usage.runTime?.maximum ?? -Infinity ) @@ -457,14 +459,14 @@ export abstract class AbstractPool< .waitTime.aggregate && { waitTime: { minimum: round( - Math.min( + min( ...this.workerNodes.map( (workerNode) => workerNode.usage.waitTime?.minimum ?? Infinity ) ) ), maximum: round( - Math.max( + max( ...this.workerNodes.map( (workerNode) => workerNode.usage.waitTime?.maximum ?? -Infinity ) diff --git a/src/utils.ts b/src/utils.ts index ae4b8637..21cf3169 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -274,5 +274,8 @@ export const secureRandom = (): number => { return webcrypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000 } -const min = (a: number, b: number): number => (a < b ? a : b) -const max = (a: number, b: number): number => (a > b ? a : b) +export const min = (...args: number[]): number => + args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity) + +export const max = (...args: number[]): number => + args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity) diff --git a/tests/utils.test.js b/tests/utils.test.js index 93e9e5c2..2101891a 100644 --- a/tests/utils.test.js +++ b/tests/utils.test.js @@ -20,7 +20,9 @@ const { isAsyncFunction, isKillBehavior, isPlainObject, + max, median, + min, round, secureRandom, sleep, @@ -311,4 +313,16 @@ describe('Utils test suite', () => { expect(randomNumber).toBeGreaterThanOrEqual(0) expect(randomNumber).toBeLessThan(1) }) + + it('Verify min() behavior', () => { + expect(min(1, 2)).toBe(1) + expect(min(2, 1)).toBe(1) + expect(min(1, 1)).toBe(1) + }) + + it('Verify max() behavior', () => { + expect(max(1, 2)).toBe(2) + expect(max(2, 1)).toBe(2) + expect(max(1, 1)).toBe(1) + }) }) -- 2.34.1