Created
January 22, 2021 02:38
-
-
Save patrixr/784b32be960864ff0e6b0311408a5b81 to your computer and use it in GitHub Desktop.
Typescript Spec Lazy Vars
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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