Skip to content

Instantly share code, notes, and snippets.

@devtin
Last active January 24, 2020 00:39
Show Gist options
  • Save devtin/0118d68e9ad56b9cd890680a31db38c4 to your computer and use it in GitHub Desktop.
Save devtin/0118d68e9ad56b9cd890680a31db38c4 to your computer and use it in GitHub Desktop.
/**
* As part of a technical screening interview I was requested to create a function
* able to calculate the total score of a game after all of the given rounds were completed
* following the criteria below:
*
* The function receives an array of strings restricted to the following operation:
* Integer: Directly represents the number of points scored this round.
* +: The points scored this round are the sum of the last two valid round's points.
* D: The points scored this round are double the last valid round's points.
* C: The last valid round's points were invalid and should not be counted towards the total score or any future operations.
*
* @parameter: {String[]} routine - Given round
* @return: {Number} result of the game
*
* @example
*
* ```js
* console.log(getTotalScoreOfTheGame(['5', '2', 'C', 'D', '+']) === 30) // => true
* ```
*/
// I'm really gonna expect an array of strings
const UnexpectedInputError = new Error(`Unexpected input`)
// Your job is to calculate the total score of the game
// after all of the rounds are complete
function getTotalScoreOfTheGame (routine) {
if (!Array.isArray(routine)) {
throw UnexpectedInputError
}
const rounds = []
routine.forEach(v => {
if (typeof v !== 'string') {
throw UnexpectedInputError
}
// Integer: Directly represents the number of points scored this round.
if (/^[\d]+$/.test(v)) {
return rounds.push(parseInt(v))
}
// "+": The points scored this round are the sum of the last two valid round's points.
if (v === '+' && rounds.length >= 2) {
return rounds.push(rounds.slice(-1)[0] + rounds.slice(-2)[0])
}
// "D": The points scored this round are double the last valid round's points.
if (v === 'D' && rounds.length > 0) {
return rounds.push(rounds.slice(-1)[0] * 2)
}
// "C": The last valid round's points were invalid and should not be counted towards the total score or any future operations.
if (v === 'C' && rounds.length > 0) {
return rounds.pop()
}
})
return rounds.reduce((a, b) => {
return a + b
}, 0)
}
console.log('Sport game test', getTotalScoreOfTheGame(['5', '2', 'C', 'D', '+']) === 30 ? '' : 'NOT', 'passed')
console.log('Sport game test', getTotalScoreOfTheGame(['5', '10', '5', 'C', 'D', '+']) === 65 ? '' : 'NOT', 'passed')
console.log('Sport game test', getTotalScoreOfTheGame(['5', '10', '5', '23', 'C', 'C', 'D', '+']) === 65 ? '' : 'NOT', 'passed')
// Sport game test passed
// Sport game test passed
// Sport game test passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment