Revert "CI: move linting after installation"
[poolifier.git] / benchmarks / internal / benchmark-utils.js
CommitLineData
2d2e32c2
JB
1const WorkerFunctions = {
2 jsonIntegerSerialization: 'jsonIntegerSerialization',
3 fibonacci: 'fibonacci',
4 factorial: 'factorial'
5}
6
74750c7f 7async function runPoolifierTest (pool, { tasks, workerData }) {
ff5e76e1
JB
8 return new Promise((resolve, reject) => {
9 let executions = 0
292ad316 10 for (let i = 1; i <= tasks; i++) {
ff5e76e1
JB
11 pool
12 .execute(workerData)
13 .then(res => {
14 executions++
15 if (executions === tasks) {
16 return resolve('FINISH')
17 }
18 return null
19 })
23ff945a
JB
20 .catch(err => {
21 console.error(err)
22 return reject(err)
23 })
ff5e76e1
JB
24 }
25 })
26}
27
bdacc2d2
JB
28function jsonIntegerSerialization (n) {
29 for (let i = 0; i < n; i++) {
30 const o = {
31 a: i
32 }
33 JSON.stringify(o)
34 }
35}
36
9bc18a6d 37function generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
c2d7d79b 38 max = Math.floor(max)
74750c7f 39 if (min) {
c2d7d79b 40 min = Math.ceil(min)
872585ea 41 return Math.floor(Math.random() * (max - min + 1)) + min
74750c7f 42 }
872585ea 43 return Math.floor(Math.random() * (max + 1))
74750c7f
JB
44}
45
bdacc2d2
JB
46/**
47 * Intentionally inefficient implementation.
48 *
7d82d90e
JB
49 * @param {number} n - The number of fibonacci numbers to generate.
50 * @returns {number} - The nth fibonacci number.
bdacc2d2
JB
51 */
52function fibonacci (n) {
53 if (n <= 1) return 1
54 return fibonacci(n - 1) + fibonacci(n - 2)
55}
56
7d82d90e
JB
57/**
58 * Intentionally inefficient implementation.
59 *
60 * @param {number} n - The number to calculate the factorial of.
61 * @returns {number} - The factorial of n.
62 */
63function factorial (n) {
64 if (n === 0) {
65 return 1
66 } else {
67 return factorial(n - 1) * n
68 }
69}
70
2d2e32c2
JB
71function executeWorkerFunction (data) {
72 switch (data.function) {
73 case WorkerFunctions.jsonIntegerSerialization:
74 return jsonIntegerSerialization(data.n || 1000)
75 case WorkerFunctions.fibonacci:
76 return fibonacci(data.n || 50)
77 case WorkerFunctions.factorial:
78 return factorial(data.n || 1000)
79 default:
80 throw new Error('Unknown worker function')
81 }
82}
83
292ad316
JB
84const LIST_FORMATTER = new Intl.ListFormat('en-US', {
85 style: 'long',
86 type: 'conjunction'
87})
88
bdacc2d2 89module.exports = {
2d2e32c2
JB
90 LIST_FORMATTER,
91 WorkerFunctions,
92 executeWorkerFunction,
bdacc2d2 93 generateRandomInteger,
2d2e32c2 94 runPoolifierTest
bdacc2d2 95}