Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix once with arguments #30

Merged
merged 3 commits into from
Apr 20, 2023
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
5 changes: 5 additions & 0 deletions .changeset/cool-socks-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@hiogawa/utils": patch
---

fix: fix `once` with arguments
2 changes: 1 addition & 1 deletion packages/utils/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hiogawa/utils",
"version": "1.4.2-pre.4",
"version": "1.4.2-pre.5",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
Expand Down
11 changes: 11 additions & 0 deletions packages/utils/src/lodash.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,4 +342,15 @@ describe("once", () => {
expect(f()).toMatchInlineSnapshot("1");
expect(count).toMatchInlineSnapshot("1");
});

it("args", () => {
let count = 0;
const f = once((increment: number) => (count = count + increment));

expect(count).toMatchInlineSnapshot("0");
expect(f(2)).toMatchInlineSnapshot("2");
expect(count).toMatchInlineSnapshot("2");
expect(f(4)).toMatchInlineSnapshot("2");
expect(count).toMatchInlineSnapshot("2");
});
});
6 changes: 3 additions & 3 deletions packages/utils/src/lodash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,13 @@ export function isNotNil<T>(value: T): value is NonNullable<T> {
export function once<F extends (...args: any[]) => any>(f: F): F {
let result: unknown;
let called = false;
const wrapper = () => {
function wrapper(...args: any[]) {
if (!called) {
result = f(...arguments);
result = f(...args);
called = true;
}
return result;
};
}
return wrapper as F;
}

Expand Down