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