Merge dependabot/npm_and_yarn/types/node-20.11.30 into combined-prs-branch
[poolifier.git] / tests / test-utils.cjs
1 const { TaskFunctions } = require('./test-types.cjs')
2
3 const waitWorkerEvents = async (pool, workerEvent, numberOfEventsToWait) => {
4 return await new Promise(resolve => {
5 let events = 0
6 if (numberOfEventsToWait === 0) {
7 resolve(events)
8 return
9 }
10 for (const workerNode of pool.workerNodes) {
11 workerNode.worker.on(workerEvent, () => {
12 ++events
13 if (events === numberOfEventsToWait) {
14 resolve(events)
15 }
16 })
17 }
18 })
19 }
20
21 const waitPoolEvents = async (pool, poolEvent, numberOfEventsToWait) => {
22 return await new Promise(resolve => {
23 let events = 0
24 if (numberOfEventsToWait === 0) {
25 resolve(events)
26 return
27 }
28 pool.emitter?.on(poolEvent, () => {
29 ++events
30 if (events === numberOfEventsToWait) {
31 resolve(events)
32 }
33 })
34 })
35 }
36
37 const sleep = async ms => {
38 return await new Promise(resolve => setTimeout(resolve, ms))
39 }
40
41 const sleepTaskFunction = async (
42 data,
43 ms,
44 rejection = false,
45 rejectionMessage = ''
46 ) => {
47 return await new Promise((resolve, reject) => {
48 setTimeout(
49 () =>
50 rejection === true
51 ? reject(new Error(rejectionMessage))
52 : resolve(data),
53 ms
54 )
55 })
56 }
57
58 const jsonIntegerSerialization = n => {
59 for (let i = 0; i < n; i++) {
60 const o = {
61 a: i
62 }
63 JSON.stringify(o)
64 }
65 return { ok: 1 }
66 }
67
68 /**
69 * Intentionally inefficient implementation.
70 * @param {number} n - The number of fibonacci numbers to generate.
71 * @returns {number} - The nth fibonacci number.
72 */
73 const fibonacci = n => {
74 if (n <= 1) return n
75 return fibonacci(n - 1) + fibonacci(n - 2)
76 }
77
78 /**
79 * Intentionally inefficient implementation.
80 * @param {number} n - The number to calculate the factorial of.
81 * @returns {number} - The factorial of n.
82 */
83 const factorial = n => {
84 if (n === 0) {
85 return 1
86 }
87 return factorial(n - 1) * n
88 }
89
90 const executeTaskFunction = data => {
91 switch (data.function) {
92 case TaskFunctions.jsonIntegerSerialization:
93 return jsonIntegerSerialization(data.n || 100)
94 case TaskFunctions.fibonacci:
95 return fibonacci(data.n || 25)
96 case TaskFunctions.factorial:
97 return factorial(data.n || 100)
98 default:
99 throw new Error('Unknown worker function')
100 }
101 }
102
103 module.exports = {
104 executeTaskFunction,
105 factorial,
106 fibonacci,
107 jsonIntegerSerialization,
108 sleep,
109 sleepTaskFunction,
110 waitPoolEvents,
111 waitWorkerEvents
112 }