uninitialized-constant
v1.0.1
Published
Utility function for creating a value container that can only be initialized once.
Downloads
5
Readme
uninitialized-constant
uninitialized-constant
is a utility function for creating a value container that can only be initialized once.
Install
$ npm install uninitialized-constant
or
$ yarn add uninitialized-constant
uninitializedConstant([defaultInitializer])
It returns a tuple with two values:
- A function that returns the value initialized in the container.
- A function that initializes the value in the container.
const [getValue, initialize] = uninitializedConstant();
initialize(42);
getValue();
// 42
Trying to get the value before it is initialized throws an error.
const [getValue, initialize] = uninitializedConstant();
getValue();
// Error: Cannot get uninitialized value.
Trying to set the value more than once throws an error.
const [getValue, initialize] = uninitializedConstant();
initialize(42);
initialize(42);
// Error: Cannot initialize more than once.
If the optional defaultInitializer
function is supplied, it will be called at most once to initialize the container if it is read before being explicitly initialized.
const [getValue, initialize] = uninitializedConstant(() => 42);
getValue();
// 42
If a container is initialized using defaultInitializer
, trying to initialize it again throws an error.
const [getValue, initialize] = uninitializedConstant(() => 42);
getValue();
// 42
initialize(42);
// Error: Cannot initialize more than once.
License
uninitialized-constant
is MIT licensed.