Created
October 3, 2018 18:21
-
-
Save rektide/49ff95dfd6984372bd307705dfe5d30c to your computer and use it in GitHub Desktop.
Lazy getters
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 { makeFoo, makeBar } from "./providers.js" | |
/** | |
* Create property `name` on `obj` that will run `provider`'s factory method the first time | |
*/ | |
function makeLazyGetter(obj, name, provider){ | |
let value | |
Object.defineProperty(obj, name, { | |
get: function(){ | |
if(!value){ | |
value= factory() | |
} | |
return value | |
} | |
}) | |
} | |
export function injectProvidersMiddleware(req){ | |
makeLazyGetter(req, "foo", makeFoo) | |
makeLazyGetter(req, "bar", makeBar) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment