Lazy Initializer
Lazy Initializer is a generic deferred object initializer, which will creates a wrapper which waits for your first time use,
then it will triggers the initialize function you defined.
The concept is similar to C#'s Lazy class,
but more transparent implementation in ES6.
Usage
Simple usage for wrapping a property in a class:
import { LazyProperty } from 'lazy-initializer';
class Schrodinger {
@LazyProperty
get cat() { return Math.random() > 0.5; }
set cat(value) {
console.log(`It is ${value ? 'alive' : 'dead'} now!`);
assert.strictEqual(value, this.cat);
}
}
const isAlive = new Schrodinger().cat;
Alternatively, if your transpiler or environment does not support ES6 decorators:
import { LazyProperty } from 'lazy-initializer';
class Schrodinger {
get cat() { return Math.random() > 0.5; }
}
LazyProperty.transform(Schrodinger, 'cat');
Also, you may manually craete a new lazy property without defining the getter/setter before:
import { LazyProperty } from 'lazy-initializer';
const someObject = {};
LazyProperty.define(someObject, 'somelazyField', () => 'boo!');
LazyProperty.define(someObject, {
someOtherLazyField: () => 'another one!',
someMoreComplicatedLazyField: {
init: () => 'More controllable behaviour!',
enumerable: false,
configurable: false,
writable: true,
},
});
Another advanced usage is wrapping a whole object (which uses proxy):
import { LazyProxy } from 'lazy-initializer';
const somethingExpensive = LazyProxy.create(() => {
return someHeavyObject;
});
const someValue = somethingExpensive.someValue();
If the lazy initialized object will be used as constructors:
import { LazyProxy } from 'lazy-initializer';
const SomeHeavyConstructor = LazyProxy.create(() => {
return Foo;
}, true);
const someValue = new SomeHeavyConstructor();
For more information, please see docs.
Installation
In your Node.js project path, run:
$ npm install --save lazy-initializer
or yarn
$ yarn add lazy-initializer
Requirements
This module make uses the new ES6 features, especially proxy,
therefore it requires at least Node.js 6+ to works.
ECMAScript 6 compatibility table
License
MIT