## [Unreleased]
+### Fixed
+
+- Ensure worker ready response can be received only once.
+- Ensure pool ready event can be emitted only once.
+
## [3.0.4] - 2023-10-20
### Changed
max,
median,
min,
+ once,
round
} from '../utils'
import { KillBehaviors } from '../worker/worker-options'
const workerInfo = this.getWorkerInfo(
this.getWorkerNodeKeyByWorkerId(message.workerId)
)
+ if (!this.started && workerInfo.ready) {
+ throw new Error(
+ `Ready response already received by worker ${
+ message.workerId as number
+ }`
+ )
+ }
workerInfo.ready = message.ready as boolean
workerInfo.taskFunctionNames = message.taskFunctionNames
if (this.ready) {
- this.emitter?.emit(PoolEvents.ready, this.info)
+ const emitPoolReadyEventOnce = once(
+ () => this.emitter?.emit(PoolEvents.ready, this.info),
+ this
+ )
+ emitPoolReadyEventOnce()
}
}
*/
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
+ }
+}
max,
median,
min,
+ once,
round,
secureRandom,
sleep
expect(max(2, 1)).toBe(2)
expect(max(1, 1)).toBe(1)
})
+
+ it('Verify once()', () => {
+ let called = 0
+ const fn = () => ++called
+ const onceFn = once(fn, this)
+ const result1 = onceFn()
+ expect(called).toBe(1)
+ expect(result1).toBe(1)
+ const result2 = onceFn()
+ expect(called).toBe(1)
+ expect(result2).toBe(1)
+ const result3 = onceFn()
+ expect(called).toBe(1)
+ expect(result3).toBe(1)
+ })
})