Skip to content

Commit

Permalink
fix: fix once with arguments (#30)
Browse files Browse the repository at this point in the history
* fix: fix `once` with args

* chore: changeset

* chore: pre
  • Loading branch information
hi-ogawa committed Apr 20, 2023
1 parent c5b8152 commit 2cfa6cb
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
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

0 comments on commit 2cfa6cb

Please sign in to comment.