-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonce.ts
More file actions
42 lines (39 loc) · 1.14 KB
/
once.ts
File metadata and controls
42 lines (39 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @fileoverview `once` — zero-argument memoizer. Caches a single
* result forever and emits `set` / `hit` debug events. Distinct from
* `memoize` because it skips the key-gen / TTL / LRU machinery that
* the general-purpose memoizer needs.
*/
import { debugLog } from '../debug/output'
/**
* Simple once() for zero-argument initialization functions.
* Caches a single result forever and emits debug-log events on hit/miss.
*
* @param fn - Zero-argument function to run once
* @returns Memoized version that only executes once
*
* @example
* import { once } from '@socketsecurity/lib/memo/once'
*
* const initialize = once(() => {
* console.log('Initializing…')
* return loadConfig()
* })
*
* initialize() // Logs "Initializing…" and returns config
* initialize() // Returns cached config (no log)
*/
export function once<Result>(fn: () => Result): () => Result {
let called = false
let result: Result
return function memoized(): Result {
if (!called) {
result = fn()
called = true
debugLog(`[once:${fn.name}] set`)
} else {
debugLog(`[once:${fn.name}] hit`)
}
return result
}
}