Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions src/function/once.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,27 @@ describe('once', () => {
expect(fn).toHaveBeenCalledOnce();
});

it('should handle functions that throw errors', () => {
it('should not cache errors and retry on subsequent calls', () => {
let callCount = 0;
const fn = vi.fn(() => {
throw new Error('Test error');
callCount++;
if (callCount < 2) {
throw new Error('Test error');
}
return 'success';
});
const onceFn = once(fn);

// First call throws
expect(() => onceFn()).toThrow('Test error');
expect(() => onceFn()).not.toThrow(); // Returns cached undefined
expect(fn).toHaveBeenCalledOnce();

// Second call succeeds and caches result
expect(onceFn()).toBe('success');
expect(fn).toHaveBeenCalledTimes(2);

// Third call returns cached result
expect(onceFn()).toBe('success');
expect(fn).toHaveBeenCalledTimes(2);
});
});
2 changes: 1 addition & 1 deletion src/function/once.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ export function once<T extends (...args: any[]) => any>(fn: T): T {
...args: Parameters<T>
): ReturnType<T> {
if (!called) {
called = true;
result = fn.apply(this, args) as ReturnType<T>;
called = true;
return result;
}
return result;
Expand Down