File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Roadmap/24 - DECORADORES/typescript Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ function greet ( name : string ) : string {
2+ return `Hello, ${ name } !` ;
3+ }
4+
5+ function logDecorator < T extends ( ...args : any [ ] ) => any > ( fn : T ) : ( ...args : Parameters < T > ) => ReturnType < T > {
6+ return function ( ...args : Parameters < T > ) : ReturnType < T > {
7+ console . log ( `Calling function: ${ fn . name } ` ) ;
8+ const result = fn ( ...args ) ;
9+ console . log ( `Function ${ fn . name } executed with result: ${ result } ` ) ;
10+ return result ;
11+ } ;
12+ }
13+
14+ const decoratedGreet = logDecorator ( greet ) ;
15+ console . log ( decoratedGreet ( "Isaac" ) ) ;
16+
17+ // ** Extra Exercise ** //
18+ function callCountDecorator < T extends ( ...args : any [ ] ) => any > ( fn : T ) : ( ...args : Parameters < T > ) => ReturnType < T > {
19+ let count = 0 ;
20+
21+ return function ( ...args : Parameters < T > ) : ReturnType < T > {
22+ count ++ ;
23+ console . log ( `Function ${ fn . name } has been called ${ count } times` ) ;
24+ return fn ( ...args ) ;
25+ } ;
26+ }
27+
28+ const decoratedGreet2 = callCountDecorator ( greet ) ;
29+ console . log ( decoratedGreet2 ( "Hiel" ) ) ;
30+ console . log ( decoratedGreet2 ( "Kurama" ) ) ;
31+ console . log ( decoratedGreet2 ( "Yusuke" ) ) ;
32+ console . log ( decoratedGreet2 ( "Kuwabara" ) ) ;
You can’t perform that action at this time.
0 commit comments