Skip to content

Instantly share code, notes, and snippets.

@patrixr
Created January 22, 2021 02:38
Show Gist options
  • Save patrixr/784b32be960864ff0e6b0311408a5b81 to your computer and use it in GitHub Desktop.
Save patrixr/784b32be960864ff0e6b0311408a5b81 to your computer and use it in GitHub Desktop.
Typescript Spec Lazy Vars
import _ from 'lodash'
interface LazyVarEntry<T = any> {
gen : () => T,
val? : T
}
interface LazyCache {
[key: string]: LazyVarEntry[]
}
let cache : LazyCache = {}
export default function lazy(name : string, gen : () => any) {
before(() => {
cache[name] = cache[name] || []
cache[name].push({
gen: gen,
val: (void 0)
})
})
after(() => {
cache[name].pop();
})
afterEach(() => {
_.each(cache, (items) => {
_.each(items, entry => entry.val = (void 0))
});
});
}
lazy.get = <T = any>(name : string) : T => {
const entry = _.last(cache[name] || []);
if (!entry) {
throw new Error(`
Attempting to lazy.get("${name}") without having it previously defined.
Expected :
lazy("${name}", () => value)
`)
}
if (!entry.val) {
entry.val = entry.gen();
}
return entry.val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment