| 313 | * @returns {FnWithoutKey<R>} cached function |
| 314 | */ |
| 315 | const cachedWithoutKey = (fn) => { |
| 316 | let inFlight = false; |
| 317 | /** @type {Error | undefined} */ |
| 318 | let cachedError; |
| 319 | /** @type {R | undefined} */ |
| 320 | let cachedResult; |
| 321 | /** @type {FnWithoutKeyCallback<R>[] | undefined} */ |
| 322 | let cachedCallbacks; |
| 323 | return (callback) => { |
| 324 | if (inFlight) { |
| 325 | if (cachedResult !== undefined) return callback(null, cachedResult); |
| 326 | if (cachedError !== undefined) return callback(cachedError); |
| 327 | if (cachedCallbacks === undefined) cachedCallbacks = [callback]; |
| 328 | else cachedCallbacks.push(callback); |
| 329 | return; |
| 330 | } |
| 331 | inFlight = true; |
| 332 | fn((err, result) => { |
| 333 | if (err) cachedError = err; |
| 334 | else cachedResult = result; |
| 335 | const callbacks = cachedCallbacks; |
| 336 | cachedCallbacks = undefined; |
| 337 | callback(err, result); |
| 338 | if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); |
| 339 | }); |
| 340 | }; |
| 341 | }; |
| 342 | |
| 343 | /** |
| 344 | * Defines the fn with key callback type used by this module. |