Skip to content
Merged
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
11 changes: 11 additions & 0 deletions src/compat/function/once.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,15 @@ describe('once', () => {
expect(resultFunc).toThrow();
expect(resultFunc).not.toThrow();
});

it('should preserve this context', () => {
const object = {
value: 42,
getValue: once(function (this: { value: number }) {
return this.value;
}),
};

expect(object.getValue()).toBe(42);
});
});
11 changes: 11 additions & 0 deletions src/function/once.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,15 @@ describe('once', () => {
expect(onceFunc()).toBeUndefined();
expect(func).toHaveBeenCalledTimes(1);
});

it('should preserve this context', () => {
const object = {
value: 42,
getValue: once(function (this: { value: number }) {
return this.value;
}),
};

expect(object.getValue()).toBe(42);
});
});
4 changes: 2 additions & 2 deletions src/function/once.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* initialize();
* // => `createApplication` is invoked once
*/
export function once<F extends (...args: any[]) => any>(func: F): F;

Check warning on line 15 in src/function/once.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 15 in src/function/once.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

/**
* Creates a function that is restricted to invoking the provided function `func` once.
Expand All @@ -31,14 +31,14 @@
* initialize(); // Logs: 'Initialized!' and returns true
* initialize(); // Returns true without logging
*/
export function once<F extends (() => any) | ((...args: any[]) => void)>(func: F): F {

Check warning on line 34 in src/function/once.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 34 in src/function/once.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
let called = false;
let cache: ReturnType<F>;

return function (...args: Parameters<F>): ReturnType<F> {
return function (this: unknown, ...args: Parameters<F>): ReturnType<F> {
if (!called) {
called = true;
cache = func(...args);
cache = func.apply(this, args);
}

return cache;
Expand Down