diff --git a/packages/util/__tests__/lazy.test.ts b/packages/util/__tests__/lazy.test.ts index e7557c0c8..243e1701c 100644 --- a/packages/util/__tests__/lazy.test.ts +++ b/packages/util/__tests__/lazy.test.ts @@ -29,4 +29,28 @@ describe('lazy', () => { expect(callback).toHaveBeenCalledOnce(); expect(cachedValue).toEqual('Lorem Ipsum'); }); + + test('GIVEN undefined callback with cached value THEN returns the same', () => { + const callback = vi.fn<() => string | undefined>(() => undefined); + + const lazyStoredValue = lazy(callback); + + lazyStoredValue(); + const cachedValue = lazyStoredValue(); + + expect(callback).toHaveBeenCalledOnce(); + expect(cachedValue).toBeUndefined(); + }); + + test('GIVEN null callback with cached value THEN returns the same', () => { + const callback = vi.fn(() => null); + + const lazyStoredValue = lazy(callback); + + lazyStoredValue(); + const cachedValue = lazyStoredValue(); + + expect(callback).toHaveBeenCalledOnce(); + expect(cachedValue).toBeNull(); + }); }); diff --git a/packages/util/src/functions/lazy.ts b/packages/util/src/functions/lazy.ts index e4f8dea6b..c47196721 100644 --- a/packages/util/src/functions/lazy.ts +++ b/packages/util/src/functions/lazy.ts @@ -13,6 +13,11 @@ // eslint-disable-next-line promise/prefer-await-to-callbacks export function lazy(cb: () => Value): () => Value { let defaultValue: Value; - // eslint-disable-next-line promise/prefer-await-to-callbacks - return () => (defaultValue ??= cb()); + let called = false; + return () => { + if (called) return defaultValue; + called = true; + // eslint-disable-next-line promise/prefer-await-to-callbacks + return (defaultValue = cb()); + }; }