lazy-getter
Lazily evaluate properties and cache the results.
Installation
npm install lazy-getter
Usage
Plain-Old Javascript
If you're using plain-old Javascript, then you can inject lazy getters into your objects via the injectLazyGetter(...)
function:
const injectLazyGetter = ; const x = {}; // Notice: this getter is computationally expensive to run!; // The getter will be evaluated the first time it is invokedconsole; // Super SLOW! // Now the result is cached. So, all subsequent calls will// just be regular property lookups.console; // Super FAST!
Decorators
If you're using Babel's Decorators Transform, then you can convert your getters to lazy getters via the @lazyGetter
decorator:
const lazyGetter = ; const x = @lazyGetter { console; let k = 0; forlet i = 0; i < 100000; ++i forlet j = 0; j < 100000; ++j ++k; console; return k; }; console; // Super SLOW!console; // Super FAST!
...Why?
Lazy Getters might seem a bit esoteric, but they are definitely very handy in certain scenarios. Here are a few examples:
Rarely-needed, but Computationally-Expensive Property
For example:
@lazyGetter { // Algorithm that returns an Array of prime factors // for the number. Might take years to run. }
Infinite Object Graphs
Sometimes, it's useful to model a problem as an infinite graph of Objects. Obviously, you can't actually contruct this infinite graph since it would require an unlimited about of time and memory. Fortunately, you can "fake it" using lazy getters:
{ return value: i @lazyGetter { return ; } } const x = ; console; // Prints: 4
Now the object graph will be constructed as needed.
FYI: zelda-lists leverages this technique to convert any iterable Object into a linked list. This allows infinite iterators to be converted into infinite object graphs, which makes it significantly easier to implement recursive algorithms.