From 27469db4f589429f5dd309187b1de2aae0275cb0 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Thu, 13 Jun 2024 23:02:09 +0200 Subject: [PATCH] refactor: add input sanity checks to mapExecute() 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 | 12 +++++++++++- tests/pools/abstract-pool.test.mjs | 11 +++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/pools/abstract-pool.ts b/src/pools/abstract-pool.ts index 8dedf205..3b79565e 100644 --- a/src/pools/abstract-pool.ts +++ b/src/pools/abstract-pool.ts @@ -1232,8 +1232,18 @@ export abstract class AbstractPool< name?: string, transferList?: readonly TransferListItem[] ): Promise { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (data == null) { + throw new TypeError('data argument must be a defined iterable') + } + if (typeof data[Symbol.iterator] !== 'function') { + throw new TypeError('data argument must be an iterable') + } + if (!Array.isArray(data)) { + data = [...data] + } return Promise.all( - [...data].map(data => this.execute(data, name, transferList)) + (data as Data[]).map(data => this.execute(data, name, transferList)) ) } diff --git a/tests/pools/abstract-pool.test.mjs b/tests/pools/abstract-pool.test.mjs index 97a2c111..8db1d2b1 100644 --- a/tests/pools/abstract-pool.test.mjs +++ b/tests/pools/abstract-pool.test.mjs @@ -1714,6 +1714,8 @@ describe('Abstract pool test suite', () => { numberOfWorkers, './tests/worker-files/thread/testMultipleTaskFunctionsWorker.mjs' ) + expect(() => pool.mapExecute()).toThrow(new TypeError('data argument must be a defined iterable')) + expect(() => pool.mapExecute(0)).toThrow(new Error('data argument must be an iterable')) let results = await pool.mapExecute([{}, {}, {}, {}]) expect(results).toStrictEqual([ { ok: 1 }, @@ -1732,6 +1734,15 @@ describe('Abstract pool test suite', () => { ]) expect(pool.info.executingTasks).toBe(0) expect(pool.info.executedTasks).toBe(8) + results = await pool.mapExecute(new Set([{ n: 10 }, { n: 20 }, { n: 30 }, { n: 40 }]), 'factorial') + expect(results).toStrictEqual([ + 3628800, + 2432902008176640000, + 2.6525285981219103e+32, + 8.159152832478977e+47, + ]) + expect(pool.info.executingTasks).toBe(0) + expect(pool.info.executedTasks).toBe(12) await pool.destroy() }) -- 2.34.1