Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

Commit

Permalink
Add lazyValue() utility function
Browse files Browse the repository at this point in the history
  • Loading branch information
surol committed Apr 11, 2020
1 parent f1c87a9 commit b2c8602
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/misc/value-providers.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,36 @@
import { valueProvider, valuesCloner, valuesProvider } from './value-providers';
import { lazyValue, valueProvider, valuesCloner, valuesProvider } from './value-providers';

describe('valueProvider', () => {
it('always returns its argument', () => {
expect(valueProvider('abc')()).toBe('abc');
});
});

describe('lazyValue', () => {

let provider: jest.Mock<string>;
let lazy: () => string;

beforeEach(() => {
provider = jest.fn(() => 'test');
lazy = lazyValue(provider);
});

it('does not call provider until requested', () => {
expect(provider).not.toHaveBeenCalled();
});
it('evaluates the value when called', () => {
expect(lazy()).toBe('test');
expect(provider).toHaveBeenCalledTimes(1);
});
it('does not re-evaluate the value', () => {
lazy();
provider.mockImplementation(() => 'other');
expect(lazy()).toBe('test');
expect(provider).toHaveBeenCalledTimes(1);
});
});

describe('valuesProvider', () => {
it('always returns its arguments', () => {
expect(valuesProvider('abc', 3)()).toEqual(['abc', 3]);
Expand Down
16 changes: 16 additions & 0 deletions src/misc/value-providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,22 @@ export function valueProvider<T>(value: T): (this: void) => T {
return (): T => value;
}

/**
* Creates a provider of lazily evaluated value.
*
* The returned function evaluates the value first time it is called. Then it just returns previously evaluated value.
*
* @param provider A no-arg function evaluating the value.
*
* @returns A function that returns the value evaluated by `provider`.
*/
export function lazyValue<T>(provider: (this: void) => T): (this: void) => T {

let get = (): T => (get = valueProvider(provider()))();

return () => get();
}

/**
* Creates a provider of arguments tuple.
*
Expand Down

0 comments on commit b2c8602

Please sign in to comment.