generated from streamich/tpl-ts-lib
-
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: 🎸 implement "once" class method decorator
- Loading branch information
Showing
3 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import {once} from '../once'; | ||
|
||
test('limits function invocation to one time only an memoizes the first result', async () => { | ||
let executions = 0; | ||
class A { | ||
@once | ||
test(value: number) { | ||
executions++; | ||
return value; | ||
} | ||
} | ||
const a = new A(); | ||
expect(a.test(123)).toBe(123); | ||
expect(a.test(1)).toBe(123); | ||
expect(a.test(2)).toBe(123); | ||
expect(executions).toBe(1); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
/** | ||
* A class method decorator that limits a method to be called only once. All | ||
* subsequent calls will return the result of the first call. | ||
*/ | ||
export function once<This, Args extends any[], Return>( | ||
target: (this: This, ...args: Args) => Return, | ||
context?: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>, | ||
) { | ||
let called = false; | ||
let res: unknown; | ||
return function (this: This, ...args: Args): Return { | ||
if (!called) { | ||
called = true; | ||
res = target.call(this, ...args); | ||
} | ||
return res as Return; | ||
}; | ||
} |