From 2cfa6cba4bdcbb06acb225d56af9e4f4753d582d Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa Date: Thu, 20 Apr 2023 11:33:14 +0900 Subject: [PATCH] fix: fix `once` with arguments (#30) * fix: fix `once` with args * chore: changeset * chore: pre --- .changeset/cool-socks-kick.md | 5 +++++ packages/utils/package.json | 2 +- packages/utils/src/lodash.test.ts | 11 +++++++++++ packages/utils/src/lodash.ts | 6 +++--- 4 files changed, 20 insertions(+), 4 deletions(-) create mode 100644 .changeset/cool-socks-kick.md diff --git a/.changeset/cool-socks-kick.md b/.changeset/cool-socks-kick.md new file mode 100644 index 00000000..ff549792 --- /dev/null +++ b/.changeset/cool-socks-kick.md @@ -0,0 +1,5 @@ +--- +"@hiogawa/utils": patch +--- + +fix: fix `once` with arguments diff --git a/packages/utils/package.json b/packages/utils/package.json index 6e50338f..8145039b 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -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", diff --git a/packages/utils/src/lodash.test.ts b/packages/utils/src/lodash.test.ts index 948ed1ff..234a54d9 100644 --- a/packages/utils/src/lodash.test.ts +++ b/packages/utils/src/lodash.test.ts @@ -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"); + }); }); diff --git a/packages/utils/src/lodash.ts b/packages/utils/src/lodash.ts index da9c1f41..a1154f9e 100644 --- a/packages/utils/src/lodash.ts +++ b/packages/utils/src/lodash.ts @@ -78,13 +78,13 @@ export function isNotNil(value: T): value is NonNullable { export function once 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; }