X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils.ts;h=80e6b9f3b5473dee9e5547930f05ce8b6b473631;hb=47c9cec4c0a1a871153e1811ec6d95c90d2c86d1;hp=7ac4ab25db67446a49b2fc42a0f219c043d4af6f;hpb=53b1b2fc0c935c958a4b6a36223dbdc44c24d926;p=poolifier.git diff --git a/src/utils.ts b/src/utils.ts index 7ac4ab25..80e6b9f3 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,8 +1,9 @@ -import os from 'node:os' +import { cpus, availableParallelism as parallelism } from 'node:os' import type { MeasurementStatisticsRequirements, WorkerChoiceStrategyOptions } from './pools/selection-strategies/selection-strategies-types' +import type { KillBehavior } from './worker/worker-options' /** * An intentional empty function. @@ -40,11 +41,11 @@ export const DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS: MeasurementStatisticsR export const availableParallelism = (): number => { let availableParallelism = 1 try { - availableParallelism = os.availableParallelism() + availableParallelism = parallelism() } catch { - const cpus = os.cpus() - if (Array.isArray(cpus) && cpus.length > 0) { - availableParallelism = cpus.length + const numberOfCpus = cpus() + if (Array.isArray(numberOfCpus) && numberOfCpus.length > 0) { + availableParallelism = numberOfCpus.length } } return availableParallelism @@ -95,3 +96,30 @@ export const isPlainObject = (obj: unknown): boolean => obj !== null && obj?.constructor === Object && Object.prototype.toString.call(obj) === '[object Object]' + +/** + * Detects whether the given value is a kill behavior or not. + * + * @typeParam KB - Which specific KillBehavior type to test against. + * @param killBehavior - Which kind of kill behavior to detect. + * @param value - Any value. + * @returns `true` if `value` was strictly equals to `killBehavior`, otherwise `false`. + */ +export const isKillBehavior = ( + killBehavior: KB, + value: unknown +): value is KB => { + return value === killBehavior +} + +/** + * Detects whether the given value is an asynchronous function or not. + * + * @param fn - Any value. + * @returns `true` if `fn` was an asynchronous function, otherwise `false`. + */ +export const isAsyncFunction = ( + fn: unknown +): fn is (...args: unknown[]) => Promise => { + return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction' +}