From 809823764586c45d49d6f53e3cda7e1e4da244f3 Mon Sep 17 00:00:00 2001 From: XhmikosR Date: Tue, 8 Feb 2022 22:20:17 +0200 Subject: [PATCH] Second attempt --- lib/getThreads.js | 35 ++++++++++++++++------------------- test/threads_test.js | 30 ++++++++++-------------------- 2 files changed, 26 insertions(+), 39 deletions(-) diff --git a/lib/getThreads.js b/lib/getThreads.js index 0e399ce..651d6c3 100644 --- a/lib/getThreads.js +++ b/lib/getThreads.js @@ -9,26 +9,23 @@ const THREADS = CPUS > 2 ? CPUS - 1 : 1; function getThreads(config) { const { threads } = config; - const defaultCheck = threads === 'auto' || - threads === -1 || - threads === '' || - threads === true || - threads === null || - typeof threads === 'undefined'; - - if (defaultCheck) { - return THREADS; - } - - if (threads === 0 || threads === 1 || threads === false) { - return 1; + switch (threads) { + case 'auto': + case -1: + case '': + case true: + case null: + case undefined: + return THREADS; + case 0: + case 1: + case false: + return 1; + default: + if (threads > 1) { + return threads; + } } - - if (threads > 1) { - return threads; - } - - throw new Error(`Invalid threads option! (${threads})`); } module.exports = getThreads; diff --git a/test/threads_test.js b/test/threads_test.js index 5c25180..c2e627c 100644 --- a/test/threads_test.js +++ b/test/threads_test.js @@ -12,7 +12,7 @@ describe('getThreads', () => { it('should use the number of available threads -1', done => { const config = {}; - for (const option of ['auto', true, -1, '', null, undefined]) { + for (const option of ['auto', -1, '', true, null, undefined]) { config.threads = option; const expected = THREADS; const actual = getThreads(config); @@ -23,14 +23,16 @@ describe('getThreads', () => { done(); }); - it('should return 1 with `threads: false`', done => { - const config = { - threads: false - }; - const expected = 1; - const actual = getThreads(config); + it('should return 1 with false, 0, or 1', done => { + const config = {}; + + for (const option of [0, 1, false]) { + config.threads = option; + const expected = 1; + const actual = getThreads(config); + assert.equal(actual, expected); + } - assert.equal(actual, expected); done(); }); @@ -44,16 +46,4 @@ describe('getThreads', () => { assert.equal(actual, expected); done(); }); - - it('should throw an error with invalid threads option', done => { - const config = {}; - - for (const option of [-2, 'foo']) { - config.threads = option; - const expected = () => getThreads(config); - assert.throws(expected, /^Error: Invalid threads/, `"thread: ${option}" failed!`); - } - - done(); - }); });