Skip to content

Commit

Permalink
feat: add lazy (#406)
Browse files Browse the repository at this point in the history
  • Loading branch information
favna committed Jul 30, 2022
1 parent e64e3d9 commit 80db17c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/utilities/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export * from './lib/isNumber';
export * from './lib/isObject';
export * from './lib/isPrimitive';
export * from './lib/isThenable';
export * from './lib/lazy';
export * from './lib/makeObject';
export * from './lib/mergeDefault';
export * from './lib/mergeObjects';
Expand Down
10 changes: 10 additions & 0 deletions packages/utilities/src/lib/lazy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Lazily creates a constant or load a module and caches it internally
* @param cb The callback to lazily run
* @returns The value returned by the callback, or the cached value if it was already initialised once.
*/
export function lazy<T>(cb: () => T) {
let defaultValue: T;

return () => (defaultValue ??= cb());
}
23 changes: 23 additions & 0 deletions packages/utilities/tests/lazy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { lazy } from '../src';

describe('lazy', () => {
test('GIVEN string callback THEN returns the same', () => {
const callback = vi.fn(() => 'Lorem Ipsum');

const lazyStoredValue = lazy(callback);

expect(lazyStoredValue()).toEqual('Lorem Ipsum');
});

test('GIVEN string callback with cached value THEN returns the same', () => {
const callback = vi.fn(() => 'Lorem Ipsum');

const lazyStoredValue = lazy(callback);

lazyStoredValue();
const cachedValue = lazyStoredValue();

expect(callback).toHaveBeenCalledOnce();
expect(cachedValue).toEqual('Lorem Ipsum');
});
});

0 comments on commit 80db17c

Please sign in to comment.