Skip to content

Commit 21374c8

Browse files
committed
✨ Add typescript solution challenge-21
1 parent bc836e6 commit 21374c8

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

2024/21-callbacks/solution.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/* eslint-disable no-console */
2+
3+
// Definir el tipo para el callback
4+
type Callback = (result: number) => void;
5+
6+
function processNumber(number: number, callback: Callback): void {
7+
const result = number * number;
8+
callback(result);
9+
}
10+
11+
function printResult(result: number): void {
12+
console.log('El resultado es:', result);
13+
}
14+
15+
// Usando la función con el callback
16+
processNumber(5, printResult);
17+
18+
// DIFICULTAD
19+
type OrderCallback = (dish: string) => void;
20+
21+
function processOrder(dish: string, onConfirmation: OrderCallback, onReady: OrderCallback, onDelivered: OrderCallback): void {
22+
// Imprimir confirmación cuando empiece el procesamiento
23+
onConfirmation(dish);
24+
25+
// Simular un tiempo aleatorio entre 1 a 10 segundos para cada etapa del proceso
26+
const randomDelay = (): number => Math.floor(Math.random() * 10000) + 1000;
27+
28+
// Simular la confirmación del pedido
29+
setTimeout(() => {
30+
onReady(dish); // Notificar que el plato está listo
31+
32+
// Simular la entrega del pedido
33+
setTimeout(() => {
34+
onDelivered(dish); // Notificar que el pedido ha sido entregado
35+
}, randomDelay());
36+
}, randomDelay());
37+
}
38+
39+
// Callbacks para manejar las etapas del pedido
40+
function confirmOrder(dish: string): void {
41+
console.log(`Pedido confirmado para: ${dish}`);
42+
}
43+
44+
function dishReady(dish: string): void {
45+
console.log(`El plato ${dish} está listo.`);
46+
}
47+
48+
function orderDelivered(dish: string): void {
49+
console.log(`El plato ${dish} ha sido entregado.`);
50+
}
51+
52+
// Usando la función con los callbacks
53+
processOrder('Pizza Margherita', confirmOrder, dishReady, orderDelivered);

0 commit comments

Comments
 (0)