uninitialized-constant
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

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:

  1. A function that returns the value initialized in the container.
  2. 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.

Readme

Keywords

none

Package Sidebar

Install

npm i uninitialized-constant

Weekly Downloads

0

Version

1.0.1

License

MIT

Unpacked Size

5.79 kB

Total Files

9

Last publish

Collaborators

  • yungsters