X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils.ts;h=5a685439ed7725c0bc305df5d86af2f670a5a9a3;hb=55d7d6002049be09a06b08da26febe2e8bfa494b;hp=d7ce5a210f2dea09290fd90a5f4eb64fcb2162d5;hpb=bfc75ccaf49d915d2b7e73c92360787b3245321a;p=poolifier.git diff --git a/src/utils.ts b/src/utils.ts index d7ce5a21..5a685439 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,5 @@ import * as os from 'node:os' -import { webcrypto } from 'node:crypto' +import { getRandomValues } from 'node:crypto' import { Worker as ClusterWorker } from 'node:cluster' import { Worker as ThreadWorker } from 'node:worker_threads' import type { @@ -226,7 +226,7 @@ export const isAsyncFunction = ( * @internal */ export const secureRandom = (): number => { - return webcrypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000 + return getRandomValues(new Uint32Array(1))[0] / 0x100000000 } /** @@ -250,3 +250,27 @@ export const min = (...args: number[]): number => */ export const max = (...args: number[]): number => args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity) + +/** + * Wraps a function so that it can only be called once. + * + * @param fn - The function to wrap. + * @param context - The context to bind the function to. + * @returns The wrapped function. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const once = ( + fn: (...args: A) => R, + context: T +): ((...args: A) => R) => { + let result: R + return (...args: A) => { + if (fn != null) { + result = fn.apply(context, args) + ;(fn as unknown as undefined) = (context as unknown as undefined) = + undefined + } + return result + } +}