"by lazy" in JavaScript? (ES6+)

Slightly off-topic, I’m asking if you can do a Kotlin thing in ES6.

I enjoy many features in Kotlin (thank you!)
One very useful one is lazy single-time instantiation using the val foo:T by lazy { bar() }

Is there a standard (and easy) way to do this in vanilla ES6? I’d love to have my various script “let myDebRef” that are eventually constructed in the script instead be constructed on-demand. I could hack together a way for each function to cache the value in the global state, but that feels… smelly.

1 Like

This isn’t horrible, but it still means all references to the variable need to instead be function calls.

const memoize = fn => {
    const cache = {};
    return (...args) => {
        const stringifiedArgs = JSON.stringify(args);
        return (cache[stringifiedArgs] = cache[stringifiedArgs] || fn(...args));