Fix random integer generator
[poolifier.git] / benchmarks / benchmarks-utils.js
1 const { WorkerFunctions } = require('./benchmarks-types')
2
3 async function runPoolifierTest (pool, { tasks, workerData }) {
4 return new Promise((resolve, reject) => {
5 let executions = 0
6 for (let i = 1; i <= tasks; i++) {
7 pool
8 .execute(workerData)
9 .then(() => {
10 executions++
11 if (executions === tasks) {
12 return resolve({ ok: 1 })
13 }
14 return null
15 })
16 .catch(err => {
17 console.error(err)
18 return reject(err)
19 })
20 }
21 })
22 }
23
24 function jsonIntegerSerialization (n) {
25 for (let i = 0; i < n; i++) {
26 const o = {
27 a: i
28 }
29 JSON.stringify(o)
30 }
31 }
32
33 function generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
34 if (max < 0) {
35 throw new RangeError('Invalid interval')
36 }
37 max = Math.floor(max)
38 if (min != null && min !== 0) {
39 if (max < min || min < 0) {
40 throw new RangeError('Invalid interval')
41 }
42 min = Math.ceil(min)
43 return Math.floor(Math.random() * (max - min + 1)) + min
44 }
45 return Math.floor(Math.random() * (max + 1))
46 }
47
48 /**
49 * Intentionally inefficient implementation.
50 *
51 * @param {number} n - The number of fibonacci numbers to generate.
52 * @returns {number} - The nth fibonacci number.
53 */
54 function fibonacci (n) {
55 if (n <= 1) return 1
56 return fibonacci(n - 1) + fibonacci(n - 2)
57 }
58
59 /**
60 * Intentionally inefficient implementation.
61 *
62 * @param {number} n - The number to calculate the factorial of.
63 * @returns {number} - The factorial of n.
64 */
65 function factorial (n) {
66 if (n === 0) {
67 return 1
68 } else {
69 return factorial(n - 1) * n
70 }
71 }
72
73 function executeWorkerFunction (data) {
74 switch (data.function) {
75 case WorkerFunctions.jsonIntegerSerialization:
76 return jsonIntegerSerialization(data.taskSize || 1000)
77 case WorkerFunctions.fibonacci:
78 return fibonacci(data.taskSize || 1000)
79 case WorkerFunctions.factorial:
80 return factorial(data.taskSize || 1000)
81 default:
82 throw new Error('Unknown worker function')
83 }
84 }
85
86 module.exports = {
87 WorkerFunctions,
88 executeWorkerFunction,
89 generateRandomInteger,
90 runPoolifierTest
91 }