Merge branch 'master' of github.com:poolifier/poolifier
[poolifier.git] / src / utils.ts
index c7efbc22638c59b55bd5e7508f3e19877c3c12a1..6d11f88cf6d964bfc9f36fe79b5c3eda3810d35b 100644 (file)
@@ -1,3 +1,4 @@
+import os from 'node:os'
 import type {
   MeasurementStatisticsRequirements,
   WorkerChoiceStrategyOptions
@@ -31,7 +32,26 @@ export const DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS: MeasurementStatisticsR
   }
 
 /**
- * Compute the median of the given data set.
+ * Returns safe host OS optimized estimate of the default amount of parallelism a pool should use.
+ * Always returns a value greater than zero.
+ *
+ * @returns The host OS optimized maximum pool size.
+ */
+export const availableParallelism = (): number => {
+  let availableParallelism = 1
+  try {
+    availableParallelism = os.availableParallelism()
+  } catch {
+    const cpus = os.cpus()
+    if (Array.isArray(cpus) && cpus.length > 0) {
+      availableParallelism = cpus.length
+    }
+  }
+  return availableParallelism
+}
+
+/**
+ * Computes the median of the given data set.
  *
  * @param dataSet - Data set.
  * @returns The median of the given data set.
@@ -51,6 +71,18 @@ export const median = (dataSet: number[]): number => {
   )
 }
 
+/**
+ * Rounds the given number to the given scale.
+ *
+ * @param num - The number to round.
+ * @param scale - The scale to round to.
+ * @returns The rounded number.
+ */
+export const round = (num: number, scale = 2): number => {
+  const rounder = Math.pow(10, scale)
+  return Math.round(num * rounder * (1 + Number.EPSILON)) / rounder
+}
+
 /**
  * Is the given object a plain object?
  *