Skip to content

Commit e986e72

Browse files
lavoieslCopilot
andauthored
feat(atomic): Add support for return types in the once util function (#6684)
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: lavoiesl <1216046+lavoiesl@users.noreply.github.com>
1 parent 2eb7f08 commit e986e72

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

packages/atomic/src/utils/utils.spec.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,46 @@ describe('utils', () => {
1717
executeOnce();
1818
expect(myFunction).toHaveBeenCalledTimes(1);
1919
});
20+
21+
it('should support arguments', () => {
22+
const fn = (num: number, str: string) => {
23+
return num * 10 + str.length;
24+
};
25+
const fnOnce = once(fn);
26+
const result = fnOnce(5, 'test');
27+
28+
expect(result).toBe(54);
29+
});
30+
31+
it('should ignore arguments if called additional times', () => {
32+
const fn = (num: number, str: string) => {
33+
return num * 10 + str.length;
34+
};
35+
const fnOnce = once(fn);
36+
const result = fnOnce(5, 'test');
37+
const result2 = fnOnce(2, 't');
38+
39+
expect(result).toBe(54);
40+
expect(result2).toBe(54);
41+
});
42+
43+
it('should support void functions', () => {
44+
const fn = (): void => {};
45+
const fnOnce = once(fn);
46+
const result: unknown = fnOnce();
47+
48+
expect(result).toBeUndefined();
49+
});
50+
51+
it('should support typed functions', () => {
52+
const fn = () => {
53+
return 123;
54+
};
55+
const fnOnce = once(fn);
56+
const result: number = fnOnce();
57+
58+
expect(result).toBe(123);
59+
});
2060
});
2161

2262
describe('#camelToKebab', () => {

packages/atomic/src/utils/utils.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@ import DOMPurify from 'dompurify';
33
/**
44
* Returns a function that can be executed only once
55
*/
6-
export function once<T extends unknown[]>(fn: (...args: T) => unknown) {
7-
let result: unknown;
6+
export function once<T extends unknown[], R>(fn: (...args: T) => R) {
7+
let result: R;
8+
let callable: ((...args: T) => R) | null = fn;
89
return function (this: unknown, ...args: T) {
9-
if (fn) {
10-
result = fn.apply(this, args);
11-
fn = () => {};
10+
if (callable) {
11+
result = callable.apply(this, args);
12+
callable = null; // Allow garbage collection
1213
}
1314
return result;
1415
};

0 commit comments

Comments
 (0)