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