Supports Stage 3 decorators natively
Create reusable @log, @validate, and @memoize decorators.
1 // @log — logs method name, args, and return value 2 function log(originalMethod: Function, context: ClassMethodDecoratorContext) { 3 const name = String(context.name); 4 return function (this: any, ...args: any[]) { 5 console.log(`[${name}] called with:`, args); 6 const result = originalMethod.apply(this, args); 7 if (result instanceof Promise) { 8 return result.then((val: any) => { 9 console.log(`[${name}] resolved:`, val); 10 return val; 11 }); 12 } 13 console.log(`[${name}] returned:`, result); 14 return result; 15 }; 16 } 17 18 // @memoize — cache return value by serialized args 19 function memoize(originalMethod: Function, context: ClassMethodDecoratorContext) { 20 const cache = new Map<string, unknown>(); 21 return function (this: any, ...args: any[]) { 22 const key = JSON.stringify(args); 23 if (cache.has(key)) { 24 console.log(`${String(context.name)}: cache hit`); 25 return cache.get(key); 26 } 27 const result = originalMethod.apply(this, args); 28 cache.set(key, result); 29 return result; 30 }; 31 } 32 33 // @retry(n) — retry async method n times on failure 34 function retry(times: number) { 35 return function (originalMethod: Function, _context: ClassMethodDecoratorContext) { 36 return async function (this: any, ...args: any[]) { 37 let lastError: Error | undefined; 38 for (let attempt = 0; attempt < times; attempt++) { 39 try { 40 return await originalMethod.apply(this, args); 41 } catch (err) { 42 lastError = err as Error; 43 console.log(`Attempt ${attempt + 1} failed: ${lastError.message}`); 44 } 45 } 46 throw lastError; 47 }; 48 }; 49 } 50 51 class MathService { 52 @log 53 add(a: number, b: number): number { return a + b; } 54 55 @memoize 56 fibonacci(n: number): number { 57 if (n <= 1) return n; 58 return this.fibonacci(n - 1) + this.fibonacci(n - 2); 59 } 60 61 @retry(3) 62 async unreliableOp(): Promise<string> { 63 if (Math.random() > 0.5) throw new Error('Random failure'); 64 return 'success'; 65 } 66 } 67 68 const svc = new MathService(); 69 console.log(svc.add(3, 4)); // logs + returns 7 70 console.log(svc.fibonacci(10)); // cached after first run 71 svc.unreliableOp().then(console.log).catch(console.error);
@log prints method name and args; @memoize caches results; @validate checks inputs
Sign in to share your feedback and join the discussion.