1
+ /**
2
+ * Interfaz que define la estructura de una tarea asíncrona
3
+ */
4
+ interface AsyncTask {
5
+ name : string ;
6
+ duration : number ;
7
+ status : 'pending' | 'running' | 'completed' ;
8
+ startTime ?: Date ;
9
+ endTime ?: Date ;
10
+ }
11
+
12
+ /**
13
+ * Clase que implementa una tarea asíncrona
14
+ */
15
+ class Task implements AsyncTask {
16
+ public status : 'pending' | 'running' | 'completed' = 'pending' ;
17
+ public startTime ?: Date ;
18
+ public endTime ?: Date ;
19
+
20
+ constructor (
21
+ public name : string ,
22
+ public duration : number
23
+ ) { }
24
+
25
+ /**
26
+ * Ejecuta la tarea y retorna una promesa
27
+ * @returns Promise<void>
28
+ */
29
+ async execute ( ) : Promise < void > {
30
+ this . status = 'running' ;
31
+ this . startTime = new Date ( ) ;
32
+
33
+ console . log ( `${ this . name } - Iniciando...` ) ;
34
+ console . log ( `${ this . name } - Durará ${ this . duration } segundos` ) ;
35
+
36
+ return new Promise < void > ( ( resolve ) => {
37
+ setTimeout ( ( ) => {
38
+ this . status = 'completed' ;
39
+ this . endTime = new Date ( ) ;
40
+ console . log ( `${ this . name } - Finalizada` ) ;
41
+ resolve ( ) ;
42
+ } , this . duration * 1000 ) ;
43
+ } ) ;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Clase que gestiona la ejecución de tareas asíncronas
49
+ */
50
+ class TaskManager {
51
+ private tasks : Map < string , Task > = new Map ( ) ;
52
+
53
+ /**
54
+ * Añade una nueva tarea al gestor
55
+ * @param name Nombre de la tarea
56
+ * @param duration Duración en segundos
57
+ */
58
+ addTask ( name : string , duration : number ) : void {
59
+ this . tasks . set ( name , new Task ( name , duration ) ) ;
60
+ }
61
+
62
+ /**
63
+ * Ejecuta una demostración básica con una sola tarea
64
+ */
65
+ async runBasicDemo ( ) : Promise < void > {
66
+ console . log ( "=== Demostración Básica ===" ) ;
67
+ const task = new Task ( "TareaEjemplo" , 2 ) ;
68
+ await task . execute ( ) ;
69
+ }
70
+
71
+ /**
72
+ * Ejecuta la dificultad extra del ejercicio
73
+ */
74
+ async runExtraChallenge ( ) : Promise < void > {
75
+ console . log ( "\n=== Dificultad Extra ===" ) ;
76
+
77
+ // Crear tareas
78
+ this . addTask ( "Tarea C" , 3 ) ;
79
+ this . addTask ( "Tarea B" , 2 ) ;
80
+ this . addTask ( "Tarea A" , 1 ) ;
81
+ this . addTask ( "Tarea D" , 1 ) ;
82
+
83
+ // Ejecutar tareas C, B y A en paralelo
84
+ const parallelTasks = [ "Tarea C" , "Tarea B" , "Tarea A" ] . map ( name =>
85
+ this . tasks . get ( name ) ! . execute ( )
86
+ ) ;
87
+
88
+ // Esperar a que terminen las tareas paralelas
89
+ await Promise . all ( parallelTasks ) ;
90
+
91
+ // Ejecutar tarea D
92
+ await this . tasks . get ( "Tarea D" ) ! . execute ( ) ;
93
+ }
94
+
95
+ /**
96
+ * Obtiene estadísticas de ejecución de las tareas
97
+ */
98
+ getStats ( ) : string {
99
+ let stats = "\nEstadísticas de ejecución:\n" ;
100
+ this . tasks . forEach ( task => {
101
+ if ( task . startTime && task . endTime ) {
102
+ const executionTime =
103
+ ( task . endTime . getTime ( ) - task . startTime . getTime ( ) ) / 1000 ;
104
+ stats += `${ task . name } : ${ executionTime . toFixed ( 2 ) } segundos\n` ;
105
+ }
106
+ } ) ;
107
+ return stats ;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Función principal que ejecuta todo el programa
113
+ */
114
+ async function main ( ) : Promise < void > {
115
+ const manager = new TaskManager ( ) ;
116
+
117
+ try {
118
+ await manager . runBasicDemo ( ) ;
119
+ await manager . runExtraChallenge ( ) ;
120
+ console . log ( manager . getStats ( ) ) ;
121
+ } catch ( error ) {
122
+ console . error ( "Error durante la ejecución:" , error ) ;
123
+ }
124
+ }
125
+
126
+ // Ejecutar el programa
127
+ main ( ) . catch ( error => console . error ( 'Error:' , error ) ) ;
128
+
129
+ // Para compilar: tsc nombrearchivo.ts
130
+ // Para ejecutar: node nombrearchivo.js
0 commit comments