perf: optimize task(s) stealing
[poolifier.git] / src / utils.ts
index d15f63c557e813aec9fdeeae7f993be8f8adedc4..dd839bc491b622aa871b876424474d24abdfb44e 100644 (file)
@@ -1,5 +1,8 @@
-import * as os from 'node:os'
 import { getRandomValues } from 'node:crypto'
+import * as os from 'node:os'
+
+import type { TaskFunctionProperties } from './utility-types.js'
+import type { TaskFunctionObject } from './worker/task-functions.js'
 import type { KillBehavior } from './worker/worker-options.js'
 
 /**
@@ -135,7 +138,7 @@ export const isPlainObject = (value: unknown): value is object =>
  *
  * @typeParam KB - Which specific KillBehavior type to test against.
  * @param killBehavior - Which kind of kill behavior to detect.
- * @param value - Any value.
+ * @param value - Unknown value.
  * @returns `true` if `value` was strictly equals to `killBehavior`, otherwise `false`.
  * @internal
  */
@@ -197,21 +200,40 @@ export const max = (...args: number[]): number =>
  * @param fn - The function to wrap.
  * @param context - The context to bind the function to.
  * @returns The wrapped function.
+ *
+ * @typeParam A - The function's arguments.
+ * @typeParam R - The function's return value.
+ * @typeParam C - The function's context.
  * @internal
  */
 // eslint-disable-next-line @typescript-eslint/no-explicit-any
-export const once = <T, A extends any[], R>(
+export const once = <A extends any[], R, C extends ThisType<any>>(
   fn: (...args: A) => R,
-  context: T
+  context: C
 ): ((...args: A) => R) => {
   let result: R
   return (...args: A) => {
     // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
     if (fn != null) {
-      result = fn.apply<T, A, R>(context, args)
+      result = fn.apply<C, A, R>(context, args)
       ;(fn as unknown as undefined) = (context as unknown as undefined) =
         undefined
     }
     return result
   }
 }
+
+export const buildTaskFunctionProperties = <Data, Response>(
+  name: string,
+  taskFunctionObject: TaskFunctionObject<Data, Response> | undefined
+): TaskFunctionProperties => {
+  return {
+    name,
+    ...(taskFunctionObject?.priority != null && {
+      priority: taskFunctionObject.priority
+    }),
+    ...(taskFunctionObject?.strategy != null && {
+      strategy: taskFunctionObject.strategy
+    })
+  }
+}