docs: refine code comments
[poolifier.git] / tests / test-utils.js
1 const { TaskFunctions } = require('./test-types.js')
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 generateRandomInteger = (max = Number.MAX_SAFE_INTEGER, min = 0) => {
59 if (max < min || max < 0 || min < 0) {
60 throw new RangeError('Invalid interval')
61 }
62 max = Math.floor(max)
63 if (min != null && min !== 0) {
64 min = Math.ceil(min)
65 return Math.floor(Math.random() * (max - min + 1)) + min
66 }
67 return Math.floor(Math.random() * (max + 1))
68 }
69
70 const jsonIntegerSerialization = n => {
71 for (let i = 0; i < n; i++) {
72 const o = {
73 a: i
74 }
75 JSON.stringify(o)
76 }
77 return { ok: 1 }
78 }
79
80 /**
81 * Intentionally inefficient implementation.
82 * @param {number} n - The number of fibonacci numbers to generate.
83 * @returns {number} - The nth fibonacci number.
84 */
85 const fibonacci = n => {
86 if (n <= 1) return n
87 return fibonacci(n - 1) + fibonacci(n - 2)
88 }
89
90 /**
91 * Intentionally inefficient implementation.
92 * @param {number} n - The number to calculate the factorial of.
93 * @returns {number} - The factorial of n.
94 */
95 const factorial = n => {
96 if (n === 0) {
97 return 1
98 }
99 return factorial(n - 1) * n
100 }
101
102 const executeTaskFunction = data => {
103 switch (data.function) {
104 case TaskFunctions.jsonIntegerSerialization:
105 return jsonIntegerSerialization(data.n || 100)
106 case TaskFunctions.fibonacci:
107 return fibonacci(data.n || 25)
108 case TaskFunctions.factorial:
109 return factorial(data.n || 100)
110 default:
111 throw new Error('Unknown worker function')
112 }
113 }
114
115 module.exports = {
116 executeTaskFunction,
117 factorial,
118 fibonacci,
119 generateRandomInteger,
120 jsonIntegerSerialization,
121 sleep,
122 sleepTaskFunction,
123 waitPoolEvents,
124 waitWorkerEvents
125 }