fix: fix possible null exception with worker_threads pools
[poolifier.git] / src / utils.ts
index d7ce5a210f2dea09290fd90a5f4eb64fcb2162d5..5a685439ed7725c0bc305df5d86af2f670a5a9a3 100644 (file)
@@ -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 = <T, A extends any[], R>(
+  fn: (...args: A) => R,
+  context: T
+): ((...args: A) => R) => {
+  let result: R
+  return (...args: A) => {
+    if (fn != null) {
+      result = fn.apply<T, A, R>(context, args)
+      ;(fn as unknown as undefined) = (context as unknown as undefined) =
+        undefined
+    }
+    return result
+  }
+}