File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
Roadmap/24 - DECORADORES/javascript Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * EJERCICIO:
3+ * Explora el concepto de "decorador" y muestra cómo crearlo
4+ * con un ejemplo genérico.
5+ */
6+
7+ function withprintResult ( func ) {
8+ return function ( ...parameters ) {
9+ console . log ( "Parámetros:" , parameters )
10+ const result = func ( ...parameters )
11+ console . log ( "Resultado:" , result )
12+ return result
13+ }
14+ }
15+
16+ function sum ( a , b ) {
17+ return a + b
18+ }
19+
20+ function multiply ( a , b ) {
21+ return a * b
22+ }
23+
24+ const sumDecorator = withprintResult ( sum )
25+ const multiplyDecorator = withprintResult ( multiply )
26+
27+ sumDecorator ( 2 , 1 )
28+ multiplyDecorator ( 2 , 3 )
29+
30+ /*
31+ * DIFICULTAD EXTRA (opcional):
32+ * Crea un decorador que sea capaz de contabilizar cuántas veces
33+ * se ha llamado a una función y aplícalo a una función de tu elección.
34+ */
35+
36+ function counterDecorator ( func ) {
37+ let counter = 0 ;
38+ return function ( ...parameters ) {
39+ counter ++ ;
40+ console . log ( `La función ha sido llamada ${ counter } veces` )
41+ return func ( ...parameters )
42+ } ;
43+ }
44+
45+ function firstFunction ( ) {
46+ console . log ( "Función ejecutada" )
47+ }
48+
49+ const decoratedFunction = counterDecorator ( firstFunction )
50+
51+ decoratedFunction ( )
52+ decoratedFunction ( )
53+ decoratedFunction ( )
You can’t perform that action at this time.
0 commit comments