Skip to content

Commit

Permalink
perf: ⚡️ improve once() decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 18, 2024
1 parent a8c99f4 commit c50e19f
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/once.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const instances = new WeakMap<any, WeakMap<any, any>>();

/**
* A class method decorator that limits a method to be called only once. All
* subsequent calls will return the result of the first call.
Expand All @@ -6,10 +8,9 @@ export function once<This, Args extends any[], Return>(
fn: (this: This, ...args: Args) => Return,
context?: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
const instances = new WeakMap<any, WeakMap<any, any>>();
return function (this: This, ...args: Args): Return {
if (!instances.has(this)) instances.set(this, new WeakMap<any, any>());
const map = instances.get(this)!;
let map = instances.get(this);
if (!map) instances.set(this, map = new WeakMap<any, any>());
if (!map.has(fn)) map.set(fn, fn.apply(this, args));
return map.get(fn);
};
Expand Down

0 comments on commit c50e19f

Please sign in to comment.