Files
Satoshi Qazi Muhammed a9d1026736 chore(papi): keep the upstream sources in upstream-src/
The pezkuwi-dev build treats any package with a src/ directory as its
own: it requires our license header on every file and builds it. These
are upstream files that must stay byte-identical to the source embedded
in dist/, so they live in upstream-src/ instead, which neither the build
nor the root tsconfig picks up.
2026-10-19 21:17:25 +04:00

45 lines
1021 B
TypeScript

import { LookupEntry } from "./lookups"
type FnWithStack<Other extends Array<any>, T> = (
input: LookupEntry,
cache: Map<number, T>,
stack: Set<number>,
...rest: Other
) => T
export const withCache =
<Other extends Array<any>, T>(
fn: FnWithStack<Other, T>,
onEnterCircular: (
cacheGetter: () => T,
circular: LookupEntry,
...rest: Other
) => T,
onExitCircular: (
outter: T,
inner: T,
circular: LookupEntry,
...rest: Other
) => T,
): FnWithStack<Other, T> =>
(input, cache, stack, ...rest) => {
const { id } = input
if (cache.has(id)) return cache.get(id)!
if (stack.has(id)) {
const res = onEnterCircular(() => cache.get(id)!, input, ...rest)
cache.set(id, res)
return res
}
stack.add(id)
let result = fn(input, cache, stack, ...rest)
stack.delete(id)
if (cache.has(id))
result = onExitCircular(result, cache.get(id)!, input, ...rest)
cache.set(id, result)
return result
}