| 1 | const { WorkerFunctions } = require('./test-types') |
| 2 | |
| 3 | class TestUtils { |
| 4 | static async waitExits (pool, numberOfExitEventsToWait) { |
| 5 | return new Promise(resolve => { |
| 6 | let exitEvents = 0 |
| 7 | for (const workerNode of pool.workerNodes) { |
| 8 | workerNode.worker.on('exit', () => { |
| 9 | ++exitEvents |
| 10 | if (exitEvents === numberOfExitEventsToWait) { |
| 11 | resolve(exitEvents) |
| 12 | } |
| 13 | }) |
| 14 | } |
| 15 | }) |
| 16 | } |
| 17 | |
| 18 | static async sleep (ms) { |
| 19 | return new Promise(resolve => setTimeout(resolve, ms)) |
| 20 | } |
| 21 | |
| 22 | static async sleepWorkerFunction ( |
| 23 | data, |
| 24 | ms, |
| 25 | rejection = false, |
| 26 | rejectionMessage = '' |
| 27 | ) { |
| 28 | return new Promise((resolve, reject) => { |
| 29 | setTimeout( |
| 30 | () => |
| 31 | rejection === true |
| 32 | ? reject(new Error(rejectionMessage)) |
| 33 | : resolve(data), |
| 34 | ms |
| 35 | ) |
| 36 | }) |
| 37 | } |
| 38 | |
| 39 | static generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { |
| 40 | if (max < min || max < 0 || min < 0) { |
| 41 | throw new RangeError('Invalid interval') |
| 42 | } |
| 43 | max = Math.floor(max) |
| 44 | if (min != null && min !== 0) { |
| 45 | min = Math.ceil(min) |
| 46 | return Math.floor(Math.random() * (max - min + 1)) + min |
| 47 | } |
| 48 | return Math.floor(Math.random() * (max + 1)) |
| 49 | } |
| 50 | |
| 51 | static jsonIntegerSerialization (n) { |
| 52 | for (let i = 0; i < n; i++) { |
| 53 | const o = { |
| 54 | a: i |
| 55 | } |
| 56 | JSON.stringify(o) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Intentionally inefficient implementation. |
| 62 | * |
| 63 | * @param {number} n - The number of fibonacci numbers to generate. |
| 64 | * @returns {number} - The nth fibonacci number. |
| 65 | */ |
| 66 | static fibonacci (n) { |
| 67 | if (n <= 1) return 1 |
| 68 | return TestUtils.fibonacci(n - 1) + TestUtils.fibonacci(n - 2) |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Intentionally inefficient implementation. |
| 73 | * |
| 74 | * @param {number} n - The number to calculate the factorial of. |
| 75 | * @returns {number} - The factorial of n. |
| 76 | */ |
| 77 | static factorial (n) { |
| 78 | if (n === 0) { |
| 79 | return 1 |
| 80 | } |
| 81 | return TestUtils.factorial(n - 1) * n |
| 82 | } |
| 83 | |
| 84 | static executeWorkerFunction (data) { |
| 85 | switch (data.function) { |
| 86 | case WorkerFunctions.jsonIntegerSerialization: |
| 87 | return TestUtils.jsonIntegerSerialization(data.n || 100) |
| 88 | case WorkerFunctions.fibonacci: |
| 89 | return TestUtils.fibonacci(data.n || 25) |
| 90 | case WorkerFunctions.factorial: |
| 91 | return TestUtils.factorial(data.n || 100) |
| 92 | default: |
| 93 | throw new Error('Unknown worker function') |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | module.exports = TestUtils |