{"id":25998547,"url":"https://github.com/dimikot/fast-typescript-memoize","last_synced_at":"2025-03-05T17:25:08.837Z","repository":{"id":143260423,"uuid":"615222421","full_name":"dimikot/fast-typescript-memoize","owner":"dimikot","description":"Fast memoization decorator and other helpers with 1st class support for Promises.","archived":false,"fork":false,"pushed_at":"2024-09-11T00:53:32.000Z","size":18,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-09-11T05:23:50.142Z","etag":null,"topics":["decorator","memoize","promise","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/fast-typescript-memoize","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dimikot.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-17T08:08:25.000Z","updated_at":"2024-09-11T00:53:35.000Z","dependencies_parsed_at":"2024-09-11T04:41:21.683Z","dependency_job_id":"a6340417-1008-407a-ad6b-24c41d885dbc","html_url":"https://github.com/dimikot/fast-typescript-memoize","commit_stats":null,"previous_names":["dimikot/fast-typescript-memoize","dmitrykoterov/fast-typescript-memoize"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimikot%2Ffast-typescript-memoize","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimikot%2Ffast-typescript-memoize/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimikot%2Ffast-typescript-memoize/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimikot%2Ffast-typescript-memoize/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dimikot","download_url":"https://codeload.github.com/dimikot/fast-typescript-memoize/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242068895,"owners_count":20066981,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["decorator","memoize","promise","typescript"],"created_at":"2025-03-05T17:25:08.010Z","updated_at":"2025-03-05T17:25:08.801Z","avatar_url":"https://github.com/dimikot.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# fast-typescript-memoize: fast memoization decorator and other helpers with 1st class support for Promises\n\n## `@Memoize()` decorator\n\nRemembers the returned value of a decorated method or getter in a hidden `this`\nobject's property, so next time the method is called, the value will be returned\nimmediately, without re-executing the method. This also works for async methods\nwhich return a Promise: in this case, multiple parallel calls to that method\nwill coalesce into one call.\n\nTo work properly, requires TypeScript v5+.\n\nThe idea of `@Memoize()` decorator is brought from\n[typescript-memoize](https://www.npmjs.com/package/typescript-memoize).\nDifferences:\n\n1. If used to memoize async methods, by default (and when\n   `clearOnResolve=true`), it clears the memoize cache as soon as the Promise\n   gets rejected (i.e. it doesn't memoize exceptions in async methods). Parallel\n   async calls to the same method will still be coalesced into one call though\n   (until the Promise rejects).\n2. A special mode is added, `clearOnResolve`. If `true`, successfully resolved\n   Promises returned from an async method will be removed from the cache as soon\n   as the method finishes. This is a convenient mode for the cases when we want\n   to coalesce multiple parallel executions of some method (e.g. when there is a\n   burst of runs), but we don't want to prevent the method from further running.\n3. Strong typing for the optional hasher handler, including types of arguments\n   and even the type of `this`.\n4. Does not support any notion of expiration.\n5. When the 1st argument of the method is an object (or when hasher handler\n   returns an object), it is not retained from GC, so you can memoize on object\n   args safely, without thinking about memory leaks.\n\n```ts\nimport { Memoize } from \"fast-typescript-memoize\";\n\nclass Class {\n  private count = 0;\n  private some = 42;\n\n  @Memoize()\n  method0() {\n    return count++;\n  }\n\n  @Memoize()\n  method1(arg: string) {\n    return count++;\n  }\n\n  @Memoize()\n  method1obj(arg: object) {\n    return count++;\n  }\n\n  @Memoize((arg1, arg2) =\u003e `${arg1}#${arg2}`)\n  method2(arg1: string, arg2: number) {\n    return count++;\n  }\n\n  @Memoize(function (arg1, arg2) { return `${this.some}:${arg1}#${arg2}`; })\n  method2this(arg1: string, arg2: number) {\n    return count++;\n  }\n\n  @Memoize()\n  async asyncMethod(arg: string) {\n    count++;\n    if (arg == \"ouch\") {\n      throw \"ouch\";\n    }\n  }\n\n  @Memoize({ clearOnResolve: true })\n  async asyncCoalescingMethod(arg: string) {\n    await delay(100);\n    count++;\n  }\n}\n\nconst obj = new Class();\nconst arg = { my: 42 };\n\nobj.method0(); // count is incremented\nobj.method0(); // count is NOT incremented\n\nobj.method1(\"abc\"); // count is incremented\nobj.method1(\"abc\"); // count is NOT incremented\nobj.method1(\"def\"); // count is incremented\n\nobj.method1obj(arg); // count is incremented, arg is not retained\nobj.method1obj(arg); // count is NOT incremented\n\nobj.method2(\"abc\", 42); // count is incremented\nobj.method2(\"abc\", 42); // count is NOT incremented\n\nobj.method2this(\"abc\", 42); // count is incremented (strongly typed `this`)\nobj.method2this(\"abc\", 42); // count is NOT incremented\n\nawait asyncMethod(\"ok\"); // count is incremented\nawait asyncMethod(\"ok\"); // count is NOT incremented\nawait asyncMethod(\"ouch\"); // count is incremented, exception is thrown\nawait asyncMethod(\"ouch\"); // count is incremented, exception is thrown\n\nawait asyncCoalescingMethod(\"ok\"); // count is incremented\nawait asyncCoalescingMethod(\"ok\"); // count is incremented again\nconst [c1, c2] = await Promise.all([\n  asyncCoalescingMethod(\"ok\"), // count is incremented\n  asyncCoalescingMethod(\"ok\"), // not incremented! coalescing parallel calls\n]);\nassert(c1 === c2);\n```\n\n## memoize0(obj, tag, func)\n\nSaves the value returned by `func()` in a hidden property `tag` (typically a\nsymbol) of `obj` object, so next time memoize0() is called, that value will be\nreturned, and `func` won't be called.\n\nThe main goal is performance and simplicity.\n\n```ts\nimport { memoize0 } from \"fast-typescript-memoize\";\n\nlet count = 0;\nconst $tag = Symbol(\"$tag\");\nconst obj = {};\nmemoize0(obj, $tag, () =\u003e count++); // count is incremented\nmemoize0(obj, $tag, () =\u003e count++); // count is NOT incremented\n```\n\n## memoize2(obj, tag, func)\n\nA simple intrusive 1-slot cache memoization helper for 2 parameters `func`. It's\nuseful when we have a very high chance of hitrate. The helper is faster (and\nmore memory efficient) than a `Map\u003cTArg1, Map\u003cTArg2, TResult\u003e\u003e` based approach\nsince it doesn't create intermediate maps.\n\nThis method works seamlessly for async functions too: the returned Promise is\neagerly memoized, so all the callers will subscribe to the same Promise.\n\nReturns the new memoized function with 2 arguments for the `tag`.\n\n```ts\nlet count = 0;\nconst $tag = Symbol(\"$tag\");\nconst obj = {};\nmemoize2(obj, $tag, (arg1, arg2) =\u003e count++)(\"abc\", 42); // count is incremented\nmemoize2(obj, $tag, (arg1, arg2) =\u003e count++)(\"abc\", 42); // count is NOT incremented\nmemoize2(obj, $tag, (arg1, arg2) =\u003e count++)(\"xyz\", 101); // count is incremented\nmemoize2(obj, $tag, (arg1, arg2) =\u003e count++)(\"abc\", 42); // count is incremented\n```\n\n## memoizeExpireUnused(func, { resolve, unusedMs })\n\nSimilar to [lodash.memoize()](https://lodash.com/docs/latest#memoize), but\nauto-expires (and removes from memory) the cached results after the provided\nnumber of inactive milliseconds. Each time we read a cached result, the\nexpiration timer starts from scratch.\n\nThis function is more expensive than `lodash.memoize()`, because it uses a JS\ntimer under the hood.\n\n```ts\nlet count = 0;\nconst func = memoizeExpireUnused((s) =\u003e count++, { resolver: (s) =\u003e s, unusedMs: 1000 });\nfunc(\"a\"); // count is incremented\nfunc(\"a\"); // count is NOT incremented\n... after 2 seconds, memory for the cached result is freed ...\nfunc(\"a\"); // count is incremented\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdimikot%2Ffast-typescript-memoize","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdimikot%2Ffast-typescript-memoize","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdimikot%2Ffast-typescript-memoize/lists"}