forked from mouredev/retos-programacion-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request mouredev#4258 from miguelriosoliveira/question/2-e…
…l-partido-de-tenis Reto mouredev#2 - TypeScript
- Loading branch information
Showing
1 changed file
with
78 additions
and
0 deletions.
There are no files selected for viewing
78 changes: 78 additions & 0 deletions
78
Retos/Reto #2 - EL PARTIDO DE TENIS [Media]/typescript/miguelriosoliveira.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
/* | ||
* Escribe un programa que muestre cómo transcurre un juego de tenis y quién lo ha ganado. | ||
* El programa recibirá una secuencia formada por "P1" (Player 1) o "P2" (Player 2), según quien | ||
* gane cada punto del juego. | ||
* | ||
* - Las puntuaciones de un juego son "Love" (cero), 15, 30, 40, "Deuce" (empate), ventaja. | ||
* - Ante la secuencia [P1, P1, P2, P2, P1, P2, P1, P1], el programa mostraría lo siguiente: | ||
* 15 - Love | ||
* 30 - Love | ||
* 30 - 15 | ||
* 30 - 30 | ||
* 40 - 30 | ||
* Deuce | ||
* Ventaja P1 | ||
* Ha ganado el P1 | ||
* - Si quieres, puedes controlar errores en la entrada de datos. | ||
* - Consulta las reglas del juego si tienes dudas sobre el sistema de puntos. | ||
*/ | ||
|
||
const POINTS = ['Love', '15', '30', '40']; | ||
|
||
function tennisMatch(sequence: string[]): void { | ||
const scores = { | ||
P1: 0, | ||
P2: 0, | ||
}; | ||
|
||
sequence.forEach(winner => { | ||
scores[winner]++; | ||
if (scores.P1 <= 3 && scores.P2 <= 3 && scores.P1 + scores.P2 !== 6) { | ||
console.log(`${POINTS[scores.P1]} - ${POINTS[scores.P2]}`); | ||
return; | ||
} | ||
if (scores.P1 === scores.P2) { | ||
console.log('Deuce'); | ||
return; | ||
} | ||
if (Math.abs(scores.P1 - scores.P2) === 1) { | ||
console.log(`Ventaja ${winner}`); | ||
return; | ||
} | ||
console.log(`Ha ganado el ${winner}`); | ||
}); | ||
} | ||
|
||
function test() { | ||
// Arrange | ||
let received = ''; | ||
const log = console.log; | ||
console.log = arg => { | ||
log(arg); | ||
received += `${arg}\n`; | ||
}; | ||
|
||
// Act | ||
tennisMatch(['P1', 'P1', 'P2', 'P2', 'P1', 'P2', 'P1', 'P1']); | ||
|
||
// Assert | ||
console.log = log; | ||
const expected = | ||
[ | ||
'15 - Love', | ||
'30 - Love', | ||
'30 - 15', | ||
'30 - 30', | ||
'40 - 30', | ||
'Deuce', | ||
'Ventaja P1', | ||
'Ha ganado el P1', | ||
].join('\n') + '\n'; | ||
if (received === expected) { | ||
console.log('✅ PASS'); | ||
} else { | ||
console.log('❌ FAIL', { expected, received }); | ||
} | ||
} | ||
|
||
test(); |